问题
Possible Duplicate:
C preprocessor: using #if inside #define?
Is there any trick to have preprocessor directives inside rhs of define ? The problem is, preprocessor folds all rhs into one long line. But maybe there is a trick ?
Example of what I'd want in the rhs is
#define MY_CHECK \
#ifndef MY_DEF \
# error MY_DEF not defined \
#endif
?
The purpose is a shortness: to have 1-line shortcut instead of multiline sequence of checks.
回答1:
As others have noted, preprocessor macros cannot expand into any other preprocessor directives; if they do you'll generally get odd errors about stray '#' characters in the input. However, sometimes there are things you can do to get what you want. If you want a macro that expands to something like:
#ifdef SOMETHING
...some code...
#endif
where some code doesn't include any preprocessor directives, you can define an IFDEF macro:
#ifdef SOMETHING
#define IFDEF_SOMETHING(X) X
#else
#define IFDEF_SOMETHING(X)
#endif
and then use IFDEF_SOMETHING(...some code...)
in your other macro.
If you have a bunch of preprocessor cruft that you want to repeat multiple times, you can stick it in its own file and then use #include "stuff"
in each spot you need it.
回答2:
It won't work (§6.10.3.4/3: "The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one ...").
If you really want to do things like this, you can run your source through something like m4 before compilation -- but I'd generally recommend against it.
回答3:
Assuming a preprocessor like the GNU C Preprocessor, then no. The manual says:
The compiler does not re-tokenize the preprocessor's output. Each preprocessing token becomes one compiler token.
来源:https://stackoverflow.com/questions/6148066/preprocessor-directives-inside-define