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,753
  • 72
  • 57
  • 129
meds
  • 21,699
  • 37
  • 163
  • 314

4 Answers4

21

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

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
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
  • 854,459
  • 170
  • 1,222
  • 1,395
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,517
  • 1
  • 40
  • 72
Paul Fultz II
  • 17,682
  • 13
  • 62
  • 59
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
  • 134,909
  • 25
  • 265
  • 421