Macros in macros

22,373

Solution 1

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.

Solution 2

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

Solution 3

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

Solution 4

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.

Share:
22,373
meds
Author by

meds

Updated on November 28, 2020

Comments

  • meds
    meds over 3 years

    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?