C++宏未正确终止宏调用

发布于 2024-11-26 21:30:37 字数 405 浏览 4 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自由范儿 2024-12-03 21:30:37

我认为这是不可能的。 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.

咆哮 2024-12-03 21:30:37

您的代码将转换为:

int foo = MACRO(1, 2;

这是错误的 - 这是宏 MACRO 的不完整(不正确终止)调用。

Your code would translate to :

int foo = MACRO(1, 2;

Which is wrong - it is an incomplete (improperly terminated) invocation of macro MACRO.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文