C++翻译阶段的混乱

发布于 2024-08-30 17:12:29 字数 426 浏览 4 评论 0原文

有人可以解释为什么以下不起作用吗?

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

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

发布评论

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

评论(4

寄意 2024-09-06 17:12:29

使用:

#define FOO L\

如果没有尾随 \,则 L 和宏替换的字符串之间将有一个空格。这是来自 g++ -E 的结果:

const wchar_t* const foo = L "bar";

Use:

#define FOO L\

without the trailing \ there will be a space between L and the string on macro substitution. This is from the result of g++ -E :

const wchar_t* const foo = L "bar";
记忆里有你的影子 2024-09-06 17:12:29

作为约翰答案的替代方案,我认为您可以按照 Microsoft 的 _T() 定义方式来定义它:

#define FOO(x)     L ## x

并像这样使用它:

FOO("bar")

这会将 L 与文本适当地连接起来。

As an alternative to John's answer, I think you could define this the way Microsoft's _T() is defined:

#define FOO(x)     L ## x

and use it like this:

FOO("bar")

This will concatenate the L with the text appropriately.

九八野马 2024-09-06 17:12:29

您收到的错误消息意味着它在执行其他操作之前正在预处理您的 #define ,它只是不知道它最终的含义是什么(在替换所有 FOO 之后) >s 与 Ls,它会查找 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 all FOOs with Ls, it looks for what L 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?

2024-09-06 17:12:29

查看预处理器的输出 (g++ -E)

# 1 "ttt.cc"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "ttt.cc"
int main()
{

  const wchar_t *const foo = L "FOO";
}

L 后面有一个空格。

Look at the output from the preprocessor (g++ -E)

# 1 "ttt.cc"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "ttt.cc"
int main()
{

  const wchar_t *const foo = L "FOO";
}

There's a space after your L.

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