c++宏连接在 gcc 下不起作用
#include <iostream>
void LOG_TRACE() { std::cout << "reach here"; }
#define LOG_LL_TRACE LOG_TRACE
#define LL_TRACE 0
#define __LOG(level) LOG_##level()
#define LOG(level) __LOG(##level)
int main()
{
LOG(LL_TRACE);
return 0;
}
该代码在 Visual Studio 下运行,但报告: test.cpp:13:1: error: Pasting "(" and "LL_TRACE" does not Give a valid preprocessing token.
我该如何修复它?
ps: 假设宏扩展为 LOG(LL_TRACE) --> __LOG(LL_TRACE) --> LOG_LL_TRACE()。
ps: 假设 LL_TRACE 必须有一个 0 值,不要删除它。
#include <iostream>
void LOG_TRACE() { std::cout << "reach here"; }
#define LOG_LL_TRACE LOG_TRACE
#define LL_TRACE 0
#define __LOG(level) LOG_##level()
#define LOG(level) __LOG(##level)
int main()
{
LOG(LL_TRACE);
return 0;
}
The code is worked under Visual Studio, but report: test.cpp:13:1: error: pasting "(" and "LL_TRACE" does not give a valid preprocessing token.
How can I fix it?
ps: The macro expansion is supposed to be LOG(LL_TRACE) --> __LOG(LL_TRACE) --> LOG_LL_TRACE().
ps: suppose LL_TRACE must have a 0 value, do not remove it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两件事导致这段代码无法在 g++ 上编译:
首先,您引用的错误是因为您想要这样:
注意没有
##
。这些井号意味着连接,但你并没有连接任何东西。只是转发一个论点。第二个错误是您必须删除
此行意味着您最终会调用 LOG(0) ,它会扩展为未定义的 LOG_0 。
Two things make this code not compile on g++:
First, the error you're quoting is because you want to have this:
Notice no
##
. Those hashmarks mean concatenate, but you're not concatenating anything. Just forwarding an argument.The second error is that you have to remove
This line means you end up calling LOG(0) which expands into LOG_0 which isn't defined.
不应该是这样吗:
有效:
Shouldn't it be :
That works: