meds
meds

Reputation: 22926

Macros in macros

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?

Upvotes: 17

Views: 28682

Answers (4)

Paul Fultz II
Paul Fultz II

Reputation: 18210

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

Upvotes: 5

Potatoswatter
Potatoswatter

Reputation: 137810

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.

Upvotes: 2

Michael Mrozek
Michael Mrozek

Reputation: 175375

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

Upvotes: 22

Alex Martelli
Alex Martelli

Reputation: 881635

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.

Upvotes: 12

Related Questions