一个奇怪的宏定义c ++

时间:2016-06-10 02:45:58

标签: c++ macros string-concatenation

编译开源项目时遇到了这个错误:

/usr/local/include/dbus-1.0/dbus/dbus-protocol.h:459:126: error: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wreserved-user-defined-literal]
#define DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE "<!DOCTYPE node PUBLIC \""DBUS_INTROSPECT_1_0_XML_PUBLIC_IDENTIFIER"\"\n\""DBUS_INTROSPECT_1_0_XML_SYSTEM_IDENTIFIER"\">\n"

通过更改上面的宏定义来解决这个问题:

-#define DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE "<!DOCTYPE node PUBLIC \""DBUS_INTROSPECT_1_0_XML_PUBLIC_IDENTIFIER"\"\n\""DBUS_INTROSPECT_1_0_XML_SYSTEM_IDENTIFIER"\">\n"
+#define DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE "<!DOCTYPE node PUBLIC \"" DBUS_INTROSPECT_1_0_XML_PUBLIC_IDENTIFIER "\"\n\"" DBUS_INTROSPECT_1_0_XML_SYSTEM_IDENTIFIER "\">\n

令我困惑的是#define本身:

#define A "" B "" C ""
这是什么? 我们可以像这样使用#define吗?

2 个答案:

答案 0 :(得分:2)

如果您使用:

#define A "Foo" B "Bar" C "Baz"

A扩展为一个字符串,其值为串联三个硬编码字符串和另外两个由宏BC定义的字符串。

如果B #define"_10_"C#define d为"_XYZ",则A会扩展为

"Foo" "_10_" "Bar" "_XYZ" "Baz"

相当于

"Foo_10_Bar_XYZBaz"

答案 1 :(得分:1)

您可以使用#define来定义包含任何内容的宏。

当使用宏时,这是否会产生可编译的有效C ++代码,这是一个完全不同的故事。