C:宏中的预处理器?
有没有办法在宏内部使用预处理器关键字?如果有某种转义字符或其他什么,我不知道。
例如,我想制作一个扩展为以下内容的宏:
#ifdef DEBUG
printf("FOO%s","BAR");
#else
log("FOO%s","BAR");
#endif
从此:
PRINT("FOO%s","BAR");
这可能吗,或者我只是疯了(每次我想显示调试消息时我都必须输入预处理器条件)?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能直接执行此操作,但您可以根据是否定义了
DEBUG
来以不同方式定义PRINT
宏:You can't do that directly, no, but you can define the
PRINT
macro differently depending on whetherDEBUG
is defined:反过来做就可以了:
Just do it the other way around:
你并不疯狂,但你从错误的角度来看待这个问题。您不能将宏扩展为具有更多预处理器参数,但您可以根据预处理器参数有条件地定义宏:
如果您有可变参数宏,则可以执行
#define DEBUG_PRINTF(...) func(__VA_ARGS__)
相反。无论哪种方式都有效。第二个允许您使用函数指针,但我无法想象为什么您需要它来达到此目的。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:
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.