9

多行原始字符串文字可以作为预处理器宏的参数吗?

#define IDENTITY(x) x

int main()
{
    IDENTITY(R"(
    )");
}

此代码不能在 g++4.7.2 和 VC++11 (Nov.CTP) 中编译。
它是编译器(词法分析器)错误吗?

4

1 回答 1

2

多行宏调用是合法的 - 因为您使用的是应该编译的原始字符串文字

有一个已知的 GCC 错误:

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52852

如果您一直在使用常规(非原始)字符串,那将是非法的。

这应该已经编译:

printf(R"HELLO
    WORLD\n");

但不是这个:

printf("HELLO
    WORLD\n");

这应该编码为

printf("HELLO\nWORLD\n"); 

如果在 HELLO 和 WORLD 之间有新的线路,或者作为

printf("HELLO "
    "WORLD\n");

如果不打算插入新行。

你想在你的文字中换行吗?如果是这样,那么你不能使用

  IDENTITY("(\n)");

C 编译器文档位于

http://gcc.gnu.org/onlinedocs/cpp.pdf

在第 3.3 节(宏参数)中指出

"The invocation of the macro need not be 
restricted to a single logical line—it can cross 
as many lines in the source file as you wish."
于 2012-11-30T17:26:12.300 回答