开发者

C: Preprocessor in Macros?

Is there a way to use preprocessor keywords inside of a macro? If there is some sort of escape character or something, I am not aware of it.

For example, I want to make 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 will have to type out the pr开发者_Go百科eprocessor conditional every time I want to show a debug message)?


You can't do that directly, no, but you can define the PRINT macro differently depending on whether DEBUG is defined:

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


Just do it the other way around:

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


You're not crazy, but you're approaching this from the wrong angle. You can't have a macro expand to have more preprocessor arguments, but you can conditionally define a macro based on preprocessor arguments:

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

If you have variadic macros, you could do #define DEBUG_PRINTF(...) func(__VA_ARGS__) instead. Either way works. The second lets you use function pointers, but I can't imagine why you'd need that for this purpose.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜