c++c++11macrosvariadic-macros

Can `#ifdef` be used inside a macro?


I only found this related question, which isn't quite what I am looking for.

I used to have macros defined inside an #ifdef statement:

#ifdef DEBUG
#   define PRINT_IF_DEBUGGING(format) printf(format);
#   define PRINTF_IF_DEBUGGING(format, ...) printf(format, __VA_ARGS__);
#else
#   define PRINT_IF_DEBUGGING(...)
#   define PRINTF_IF_DEBUGGING(...)
#endif

Now, I want to do the inverse, to have the #ifdef statements inside the macros. Something like this:

#define PRINT_IF_DEBUGGING(format, ...) \
#if defined(DEBUG) print(format); #endif
#define PRINTF_IF_DEBUGGING(format, ...) \
#if defined(DEBUG) printf(format, __VA_ARGS__); #endif

However, I am having an issue using __VA_ARGS__ inside the #ifdef defined.

error: '#' is not followed by a macro parameter
 #define PRINT_IF_DEBUGGING(format, ...)
error: '#' is not followed by a macro parameter
 #define PRINTF_IF_DEBUGGING(format, ...)
warning: __VA_ARGS__ can only appear in the expansion of a C++11 variadic macro
 #if defined(DEBUG) printf(format, __VA_ARGS__); #endif

Is this possible?


Solution

  • You can't use #ifdef inside of #define , so no, this is not possible. The first code you showed is the correct solution.