#if 0 作为定义 [英] #if 0 as a define
问题描述
我需要一种方法来定义一个 FLAGS_IF
宏(或等效的),以便
I need a way to define a FLAGS_IF
macro (or equivalent) such that
FLAGS_IF(expression)
<block_of_code>
FLAGS_ENDIF
在调试中编译时(例如使用特定的编译器开关)编译为
when compiling in debug (e.g. with a specific compiler switch) compiles to
if (MyFunction(expression))
{
<block_of_code>
}
而在发布时不会产生任何指令,就像这样
whereas in release does not result in any instruction, just as it was like this
#if 0
<block_of_code>
#endif
由于我对 C/C++ 预处理器的问题一无所知,我想不出任何幼稚的方法(因为 #define FLAGS_IF(x) #if 0
没有甚至编译)这样做,你能帮忙吗?
In my ignorance on the matter of C/C++ preprocessors I can't think of any naive way (since #define FLAGS_IF(x) #if 0
does not even compile) of doing this, can you help?
我需要一个解决方案:
- 如果
*/
存在于<block_of_code>
中,则不会搞砸 - 即使在任何深度的内联函数中,也肯定会在发布时生成 0 条指令(我猜这不包括
if (false){<block_of_code>}
对吧?) - 尽可能符合标准
推荐答案
以下应该做你想做的:
#ifdef DEBUG
# define FLAGS_IF(x) if (MyFunction((x))) {
# define FLAGS_ENDIF }
#else
# define FLAGS_IF(x) if(0) {
# define FLAGS_ENDIF }
#endif
if(0) 应该变成无指令,或者至少在大多数编译器上都是这样.
The if(0) should turn into no instructions, or at least it does so on most compilers.
编辑:Hasturkun 评论说您实际上并不需要 FLAGS_ENDIF,因此您可以这样编写代码:
Edit: Hasturkun commented that you don't really need the FLAGS_ENDIF, so you would instead write your code like this:
FLAGS_IF(expression) {
<block_of_code>
}
使用以下宏:
#ifdef DEBUG
# define FLAGS_IF(x) if (MyFunction((x)))
#else
# define FLAGS_IF(x) if(0)
#endif
这篇关于#if 0 作为定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!