C语言 c 定义多行宏?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16685211/
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-09-02 06:25:48  来源:igfitidea点击:

c define multiline macro?

cmacros

提问by Jichao

#define DEBUG_BREAK(a)\
    if ((a)) \
{\
    __asm int 3;\
}

I have defined a macro as above, and try to use it

我已经定义了一个宏,并尝试使用它

#include "test_define.h"
int main()
{
    DEBUG_BREAK(1 == 1);
    return 0;
}

But this sample will not compile. The compiler would complain the parenthesis is not closed. If I add another }in the end of the source file, it compiles.

但是这个示例不会编译。编译器会抱怨括号没有关闭。如果我}在源文件的末尾添加另一个,它会编译。

What's wrong with this macro?

这个宏有什么问题?

回答by raj raj

The macro

#define DEBUG_BREAK(a)\
    if ((a)) \
    __asm int 3;

works fine but

工作正常,但

#define DEBUG_BREAK(a)\
    if ((a)) \
{\
    __asm int 3;\
}

doesn't! And I think anyone could guess why!! The new line operator is the problem making guy!

没有!我想任何人都可以猜到为什么!!新的线路操作员是制造问题的人!

It takes

它需要

 __asm int 3;\
}

as

作为

__asm int 3; }

where ;comments out what follows it (in assembly). So we will miss a }then.

where;注释掉它后面的内容(在汇编中)。所以我们会错过一次}

回答by Bathsheba

Check there is no white space after each backslash. I often fall for this.

检查每个反斜杠后没有空格。我经常为此而堕落。

You might even need a single space before the backslash.

您甚至可能需要在反斜杠前留一个空格。

回答by selbie

#define DEBUG_BREAK(a)\
if ((a)) \
{\
    __asm \
    { \
        int 3;\
    } \
}

Or.... (since you are on Windows, just use the DebugBreak function...)

或者....(因为你在 Windows 上,只需使用 DebugBreak 函数...)

#define DEBUG_BREAK(a) {if ((a)) DebugBreak();}

回答by akhil

Please try this

请试试这个

#define DEBUG_BREAK(a)\
    if ((a)) \
    __asm int 3;

回答by akalenuk

That's weird, but getting {int 3} into brackets helps. And combining macro into singleliner doesn't. So it should be something about assembly, not the multilining.

这很奇怪,但是将 {int 3} 放入括号会有所帮助。将宏组合成单行代码则不然。所以它应该是关于组装的,而不是多线。

回答by Mats Petersson

Rewrite it as an inline function:

将其重写为内联函数:

inline void DEBUG_BREAK(bool b)
{
    if (b) 
    {
        __asm int 3
    }
}

You may want to replace __asm int 3with DebugBreak(), as that is the official MS function to do this.

您可能想要替换__asm int 3DebugBreak(),因为这是执行此操作的官方 MS 函数。