C++翻译阶段混乱

bla*_*ecl 4 c++ c-preprocessor

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

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
}
Run Code Online (Sandbox Code Playgroud)

我认为预处理是在比字符串文字操作和一般令牌翻译更早的翻译阶段完成的.

编译器不会或多或少看到这个:

int main()
{
  const wchar_t* const foo = L"bar"; 
}
Run Code Online (Sandbox Code Playgroud)

如果有人能引用标准的解释,那就太好了.

cod*_*ict 6

使用:

#define FOO L\
Run Code Online (Sandbox Code Playgroud)

没有尾随,宏替换\之间会有一个空格L和字符串.这是由以下结果g++ -E:

const wchar_t* const foo = L "bar";
Run Code Online (Sandbox Code Playgroud)

  • 确保在此定义和下一行之间留一个空行,否则宏将继续.我过去曾多次使用它来制作多行宏. (2认同)