简体   繁体   English

C:宏中的预处理器?

[英]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 preprocessor 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: 你不能直接这样做,不,但你可以根据是否定义DEBUG来不同地定义PRINT宏:

#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. 如果你有可变参数宏,你可以#define DEBUG_PRINTF(...) func(__VA_ARGS__) Either way works. 无论哪种方式都有效。 The second lets you use function pointers, but I can't imagine why you'd need that for this purpose. 第二个让你使用函数指针,但我无法想象为什么你需要它为此目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM