15

Is it possible to put a macro in a macro in c++?

Something like:

#define Something\
#ifdef SomethingElse\ //do stuff \
#endif\

I tried and it didn't work so my guess is it doesn't work, unless there's some sort of syntax that can fix it?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
meds
  • 19,766
  • 31
  • 144
  • 291

4 Answers4

20

Macros, yes. Preprocessor directives, which are what you posted, no

Michael Mrozek
  • 161,243
  • 28
  • 165
  • 171
12

No, but you can simply refactor this by pulling the #ifdef out as the toplevel, and using two different #define Something ... versions for the true and false branches of the #ifdef.

Alex Martelli
  • 811,175
  • 162
  • 1,198
  • 1,373
4

You can't use preprocessor directives in macros, but if we want to check if SomethingElse is defined and call a different macro, you could accomplish it like this(requires a c99 preprocessor and Boost.Preprocessor library):

#define PP_CHECK_N(x, n, ...) n
#define PP_CHECK(...) PP_CHECK_N(__VA_ARGS__, 0,)

//If we define SomethingElse, it has to be define like this
#define SomethingElse ~, 1,

#define Something \
BOOST_PP_IF(PP_CHECK(SomethingElse), MACRO1, MACRO2)

If SomethingElse is defined it will call MACRO1, otherwise it will call MACRO2. For this to work, SomethingElse has to be defined like this:

#define SomethingElse ~, 1,

By the way, this won't work in Visual Studio, because of a bug in their compiler, there is a workaround here: http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement

Arafangion
  • 11,014
  • 1
  • 37
  • 71
Paul Fultz II
  • 17,010
  • 12
  • 57
  • 58
2

No. I answered this in c++ macros with memory?

If you want to inspect or alter the preprocessing environment, in other words to define a preprocessing subroutine rather than a string-replacement macro, you need to use a header, although the legitimate reasons for doing so are few and far between.

Community
  • 1
  • 1
Potatoswatter
  • 131,100
  • 23
  • 249
  • 407