C++ 多行预处理器宏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10419530/
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
Multi line preprocessor macros
提问by noisy cat
How to make multi line preprocessor macro? I know how to make one line:
如何制作多行预处理器宏?我知道如何制作一行:
#define sqr(X) (X*X)
but I need something like this:
但我需要这样的东西:
#define someMacro(X)
class X : public otherClass
{
int foo;
void doFoo();
};
How can I get this to work?
我怎样才能让它发挥作用?
This is only an example, the real macro may be very long.
这只是一个例子,真正的宏可能很长。
回答by Ed S.
You use \
as a line continuation escape character.
您\
用作换行符转义符。
#define swap(a, b) { \
(a) ^= (b); \
(b) ^= (a); \
(a) ^= (b); \
}
EDIT: As @abelenky pointed out in the comments, the \
character must be the last character on the line. If it is not (even if it is just white space afterward) you will get confusing error messages on each line after it.
编辑:正如@abelenky 在评论中指出的那样,该\
字符必须是该行的最后一个字符。如果不是(即使它之后只是空白),您将在其后的每一行上看到令人困惑的错误消息。
回答by Kerrek SB
You can make a macro span multiple lines by putting a backslash (\
) at the end of each line:
您可以通过\
在每行末尾放置一个反斜杠 ( )来使宏跨越多行:
#define F(x) (x) \
* \
(x)
回答by jiveturkey
PLEASE NOTEas Kerrek SB and coaddict pointed out, which should have been pointed out in the accepted answer,
ALWAYSplace braces around your arguments. The sqr example is the simple example taught in CompSci courses.
Here's the problem: If you define it the way you did what happens when you say "sqr(1+5)"?
You get "1+5*1+5" or 11
If you correctly place braces around it, #definesqr(x) ((x)*(x))
you get ((1+5) * (1+5)) or what we wanted 36 ...beautiful.
Ed S. is going to have the same problem with 'swap'
请注意,正如 Kerrek SB 和 coaddict 指出的那样,应该在已接受的答案中指出这一点,始终在您的论点周围加上
大括号。sqr 示例是 CompSci 课程中教授的简单示例。
问题是:如果你按照你的方式定义它,当你说“sqr(1+5)”时会发生什么?你得到 "1+5*1+5" 或 11
如果你正确地在它周围放置大括号,#definesqr(x) ((x)*(x))
你得到 ((1+5) * (1+5)) 或我们想要的 36 ...漂亮。
Ed S. 将遇到与“交换”相同的问题
回答by codaddict
You need to escape the newline at the end of the line by escaping it with a \
:
您需要通过使用 转义来转义行尾的换行符\
:
#define sqr(X) \
((X)*(X))