C++宏未正确终止宏调用
在C++中是否有一种机制允许表达非终止宏? 这是一个人为的示例:
#define MACRO(x, y) x + y
#define MACROC1(x) MACRO(x,
#define MACROC2(y) y)
//...expecting 3
int foo = MACROC1(1) MACROC2(2);
我从 MSVC 收到错误错误终止宏调用。
当我运行 cl -E file.cpp 时,我看到生成了以下代码:
int c = 1 + 1 + 2);
在 Visual Studio 中,编译失败并出现错误: 错误 C2059:语法错误:')' IntelliSense:未正确终止宏调用
In C++ is there a mechanism to allow non terminated macros to be expressed?
This is a contrived example:
#define MACRO(x, y) x + y
#define MACROC1(x) MACRO(x,
#define MACROC2(y) y)
//...expecting 3
int foo = MACROC1(1) MACROC2(2);
I receive the error improperly terminated macro invocation from MSVC.
When I run cl -E file.cpp I see that the code below has been generated:
int c = 1 + 1 + 2);
In visual studio compilation fails with errors:
error C2059: syntax error : ')'
IntelliSense: improperly terminated macro invocation
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是不可能的。 C 预编译器深度优先扩展宏,因此在考虑 MACROC2 之前,MACROC1 将被完全扩展。然后,它会找到参数列表不完整的宏并抛出错误。
一般来说,您应该避免定义构建其他宏调用的宏。编译器往往不同意这些含义。
I don't think this is possible. The C precompiler expands macros depth-first, so the MACROC1 will be full expanded before the MACROC2 is even considered. Then, it will find the MACRO with and incomplete argument list and throws an error.
Generally speaking, you should avoid defining macros that build other macro calls. Compilers tend not to agree in what those mean.
您的代码将转换为:
这是错误的 - 这是宏 MACRO 的不完整(不正确终止)调用。
Your code would translate to :
Which is wrong - it is an incomplete (improperly terminated) invocation of macro MACRO.