C: Preprocessor in macros?

Is there a way to use preprocessor keywords inside a macro? If there is some kind of escape character or something else, I don't know about that.

For example, I want to create a macro that expands to this:

#ifdef DEBUG
    printf("FOO%s","BAR");
#else
    log("FOO%s","BAR");
#endif

from this:

PRINT("FOO%s","BAR");

Is this possible, or am I just crazy (and I have to enter a conditional preprocessor every time I want to show a debug message)?

+3
source share
3 answers

You cannot do this directly, no, but you can define a macro PRINTdifferently depending on whether it is defined DEBUG:

#ifdef DEBUG
    #define PRINT(...) printf(__VA_ARGS__)
#else 
    #define PRINT(...) log(__VA_ARGS__)
#endif
+6
source

Just do it the other way around:

#ifdef DEBUG
    #define PRINT printf
#else
    #define PRINT log
#endif
+2
source

You are not crazy, but you are approaching this from the wrong angle. You cannot have macros to have more preprocessor arguments, but you can conditionally define a macro based on the preprocessor arguments:

#ifdef DEBUG
# define DEBUG_PRINT printf
#else
# define DEBUG_PRINT log
#endif

If you have variable macros, you can do it #define DEBUG_PRINTF(...) func(__VA_ARGS__). Anyway. The second allows you to use function pointers, but I can’t imagine why you need it.

0
source

All Articles