Home > Net >  Can `#ifdef` be used inside a macro?
Can `#ifdef` be used inside a macro?

Time:05-17

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?

CodePudding user response:

This should really be a comment, but I can't format that in a way that will allow me to say what I want to say, so I'm answering instead.

Anyway, just change this:

#if defined(DEBUG) print(format); #endif

to this:

#if defined(DEBUG)
    print(format);
#endif

and so on, and that should fix it.

CodePudding user response:

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

  • Related