Multiple preprocessor directives on one line in C++

僤鯓⒐⒋嵵緔 提交于 2019-12-03 16:38:57

问题


A hypothetical question: Is it possible to have a C++ program, which includes preprocessor directives, entirely on one line?

Such a line would look like this:

#define foo #ifdef foo #define bar #endif

What are the semantics of such a line?

Further, are there any combinations of directives which are impossible to construct on one line?

If this is compiler-specific then both VC++ and GCC answers are welcome.


回答1:


A preprocessing directive must be terminated by a newline, so this is actually a single preprocessing directive that defines an object-like macro, named foo, that expands to the following token sequence:

# ifdef foo # define bar # endif

Any later use of the name foo in the source (until it is #undefed) will expand to this, but after the macro is expanded, the resulting tokens are not evaluated as a preprocessing directive.

This is not compiler-specific; this behavior is defined by the C and C++ standards.




回答2:


Preprocessor directives are somewhat different than language statements, which are terminated by ; and use whitespace to delimit tokens. In the case of the preprocessor, the directive is terminated by a newline so it's impossible to do what you're attempting using the C++ language itself.

One way you could kind of simulate this is to put your desired lines into a separate header file and then #include it where you want. The separate header still has to have each directive on one line, but the point where you include it is just a single line, effectively doing what you asked.

Another way to accomplish something like that is to have a pre-C++ file that you use an external process to process into a C++ source file prior to compiling with your C++ compiler. This is probably rather more trouble than it's worth.



来源:https://stackoverflow.com/questions/3532309/multiple-preprocessor-directives-on-one-line-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!