C++翻译阶段的混乱
有人可以解释为什么以下不起作用吗?
int main() // Tried on several recent C++ '03 compilers.
{
#define FOO L
const wchar_t* const foo = FOO"bar"; // Will error out with something like: "identifier 'L' is undefined."
#undef FOO
}
我认为预处理是在比字符串文字操作和一般标记翻译更早的翻译阶段完成的。
编译器不会或多或少地看到这一点:
int main()
{
const wchar_t* const foo = L"bar";
}
如果有人可以引用标准中的解释,那就太好了。
Can someone explain why the following doesn't work?
int main() // Tried on several recent C++ '03 compilers.
{
#define FOO L
const wchar_t* const foo = FOO"bar"; // Will error out with something like: "identifier 'L' is undefined."
#undef FOO
}
I thought that preprocessing was done in an earlier translation phase than string literal operations and general token translation.
Wouldn't the compiler be more or less seeing this:
int main()
{
const wchar_t* const foo = L"bar";
}
It would be great if someone could cite an explanation from the standard.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用:
如果没有尾随
\
,则L
和宏替换的字符串之间将有一个空格。这是来自g++ -E
的结果:Use:
without the trailing
\
there will be a space betweenL
and the string on macro substitution. This is from the result ofg++ -E
:作为约翰答案的替代方案,我认为您可以按照 Microsoft 的 _T() 定义方式来定义它:
并像这样使用它:
这会将 L 与文本适当地连接起来。
As an alternative to John's answer, I think you could define this the way Microsoft's _T() is defined:
and use it like this:
This will concatenate the L with the text appropriately.
您收到的错误消息意味着它在执行其他操作之前正在预处理您的
#define
,它只是不知道它最终的含义是什么(在替换所有FOO
之后) >s 与L
s,它会查找L
的含义,但无法弄清楚)。编译器正在查看您的第二段代码,它只是不知道此时
L"bar"
的含义。您确定所有内容都已正确定义并包含吗?
The error message you're getting means that it is preprocessing your
#define
before it does anything else, it just doesn't know what it ends up meaning (after replacing allFOO
s withL
s, it looks for whatL
means and can't figure it out).The compiler is seeing your second bit of code, it just doesn't know what
L"bar"
means at that point.Are you sure everything is defined and included properly?
查看预处理器的输出 (g++ -E)
L 后面有一个空格。
Look at the output from the preprocessor (g++ -E)
There's a space after your L.