val*_*rio 12 macros c-preprocessor
我需要一种方法来定义一个FLAGS_IF宏(或等价物)
FLAGS_IF(expression)
<block_of_code>
FLAGS_ENDIF
Run Code Online (Sandbox Code Playgroud)
在调试中编译时(例如,使用特定的编译器开关)编译为
if (MyFunction(expression))
{
<block_of_code>
}
Run Code Online (Sandbox Code Playgroud)
而在发布中不会产生任何指令,就像它是这样的
#if 0
<block_of_code>
#endif
Run Code Online (Sandbox Code Playgroud)
在我对C/C++预处理器问题的无知中,我无法想到这样做的任何天真的方式(因为#define FLAGS_IF(x) #if 0甚至没有编译),你能帮忙吗?
我需要一个解决方案:
*/内部存在,不会搞砸<block_of_code>if (false){<block_of_code>}吗?)Han*_*ant 30
宏是非常邪恶的,但没有什么比使用宏来模糊控制语句和块更邪恶了.编写这样的代码是没有充分理由的.做到这一点:
#ifdef DEBUG
if (MyFunction(expression))
{
<block_of_code>
}
#endif
Run Code Online (Sandbox Code Playgroud)
bra*_*amp 11
以下应该做你想要的:
#ifdef DEBUG
# define FLAGS_IF(x) if (MyFunction((x))) {
# define FLAGS_ENDIF }
#else
# define FLAGS_IF(x) if(0) {
# define FLAGS_ENDIF }
#endif
Run Code Online (Sandbox Code Playgroud)
if(0)应该变成没有指令,或者至少它会在大多数编译器中这样做.
编辑:Hasturkun评论说你真的不需要FLAGS_ENDIF,所以你会改为编写你的代码:
FLAGS_IF(expression) {
<block_of_code>
}
Run Code Online (Sandbox Code Playgroud)
使用以下宏:
#ifdef DEBUG
# define FLAGS_IF(x) if (MyFunction((x)))
#else
# define FLAGS_IF(x) if(0)
#endif
Run Code Online (Sandbox Code Playgroud)
我可能会这样做:
#ifdef DEBUG
const bool IS_RELEASE_MODE = false;
#else
const bool IS_RELEASE_MODE = true;
#endif
if (IS_RELEASE_MODE && MyFunction(expression))
{
...
}
Run Code Online (Sandbox Code Playgroud)
这应该从发布版本中编译出来,因为if(false && f())与if(false)相同,后者在大多数编译器中得到优化.
如果您坚持不在代码内部使用#ifdef,那就是这样.否则,我更喜欢别人发布的#ifdef DEBUG if(MyFunction(expression)){...} #endif.
| 归档时间: |
|
| 查看次数: |
3865 次 |
| 最近记录: |