关于c语言预编译符号##的问题
如下简单的几行代码:
#include <stdio.h>
#include <stdlib.h>
#define MSGVAR( xx_level, xx_module,xx_fmt, ... ) \
do { \
printf( xx_module##": %s:%d: "##xx_fmt"\n", __FILE__, __LINE__, __VA_ARGS__ ); \
} while (0)
int main( int argc ,char* argv[] )
{
MSGVAR( 1, "xx", "%d,%d", 12,34);
}
在vs2005中能编译通过顺利运行,但是在linux下, gcc -o test test.c 却编译失败,失败的消息是:
test.c:12:1: error: pasting ""xx"" and "": %s:%d: "" does not give a valid
preprocessing token
test.c:12:1: error: pasting "": %s:%d: "" and ""%d,%d"" does not give a
valid preprocessing token
test.c:13:2: warning: no newline at end of file
于是我想是不是我用##语法用错了,所以我生成预处理文件分析一下,gcc test.c -E,输出结果:
int main( int argc ,char* argv[] )
{
test.c:12:1: error: pasting ""xx"" and "": %s:%d: "" does not give a valid
preprocessing token
test.c:12:1: error: pasting "": %s:%d: "" and ""%d,%d"" does not give a
valid preprocessing token
do { printf( "xx"": %s:%d: " "%d,%d""\n", "test.c", 12, 12,34 ); } while
(0);
test.c:13:2: warning: no newline at end of file
}
问题就出来了,我把test.c中用到了宏的那一行,用扩展以后的宏替换,
也就是把MSGVAR( 1, "xx", "%d,%d", 12,34);替换为:do { printf( "xx"": %s:%d: " "%d,%d""\n", "test.c", 12, 12,34 ); } while(0);
gcc -o test test.c ,ok直接通过。
有人能告诉我这是为什么吗。