11

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.

Community
  • 1
  • 1
Andrei
  • 8,288
  • 10
  • 33
  • 41

3 Answers3

14

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.

Chris Dodd
  • 111,130
  • 12
  • 123
  • 212
5

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.

Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067
4

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.

detly
  • 27,996
  • 15
  • 89
  • 145