C++ 宏中的“#ifdef”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7246512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:40:36  来源:igfitidea点击:

"#ifdef" inside a macro

c++c-preprocessor

提问by JasonGenX

Possible Duplicate:
#ifdef inside #define

可能重复:
#ifdef 内 #define

How do I use the character "#" successfully inside a Macro? It screams when I do something like that:

如何在宏中成功使用字符“#”?当我做这样的事情时它会尖叫:

#define DO(WHAT)        \
#ifdef DEBUG        \                           
  MyObj->WHAT()         \       
#endif              \

回答by Roger Lipscombe

You can't do that. You have to do something like this:

你不能那样做。你必须做这样的事情:

#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT) do { } while(0)
#endif

The do { } while(0)avoids empty statements. See this question, for example.

do { } while(0)避免了空语句。例如,请参阅此问题

回答by Oliver Charlesworth

It screams because you can't do that.

它尖叫是因为你不能那样做。

I suggest the following as an alternative:

我建议以下作为替代方案:

#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT)
#endif

回答by Paul Manta

It seems that what you want to do can be achieved like this, without running into any problems:

看来你想做的事情可以这样实现,不会遇到任何问题:

#ifdef DEBUG
#    define DO(WHAT) MyObj->WHAT()
#else
#    define DO(WHAT) while(false)
#endif

Btw, better use the NDEBUGmacro, unless you have a more specific reason not to. NDEBUGis more widely used as a macro that means no-debugging. For example the standard assertmacro can be disabled by defining NDEBUG. Your code would become:

顺便说一句,最好使用NDEBUG宏,除非您有更具体的理由不这样做。NDEBUG更广泛地用作宏,这意味着无需调试。例如,assert可以通过定义来禁用标准宏NDEBUG。你的代码会变成:

#ifndef NDEBUG
#    define DO(WHAT) MyObj->WHAT()
#else
#    define DO(WHAT) while(false)
#endif

回答by antlersoft

You can do the same thing like this:

你可以做同样的事情:

#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT)
#endif

回答by Miguel

How about:

怎么样:

#ifdef DEBUG
#define DO(WHAT) MyObj->WHAT()
#else
#define DO(WHAT)
#endif