为什么我的宏不能编译?

时间:2015-05-20 13:04:42

标签: c macros c-preprocessor predefined-macro

#define LINE_FILE ("Line"#__LINE__"of file"__FILE__)

int main(void)
{
    printf("%s", LINE_FILE);
}

我的期望:

  

LINE_FILE =" 文件名的文件 "

printf()可以输出此字符串。

http://ww2.sinaimg.cn/large/005FchG6gw1esb0pvwxr3j30he06jjt7.jpg

4 个答案:

答案 0 :(得分:4)

F[,,1] ,F[,,2].......... F[,,31] (or could be F[,,28])不会扩展为"字符串",而是扩展为__LINE__

要解决此问题,您可能希望执行以下操作:

int

的更多(gcc)详情

答案 1 :(得分:3)

您需要一个stringify帮助器

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

然后

#define LINE_FILE ("Line" STR(__LINE__)"of file"__FILE__)

答案 2 :(得分:0)

AFAIK你不能在预处理器上做到这一点,通常的方法是:

    printf("Line %d of file %s", __LINE__, __FILE__);

答案 3 :(得分:0)

要调试宏,您可以单独使用C预处理器。

linenumber.c

#define LINE_FILE_WRONG ("Line"#__LINE__"of file"__FILE__)

// solution of LPs
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#define LINE_FILE ("Line " STR(__LINE__) " of file " __FILE__)

LINE_FILE_WRONG
LINE_FILE

运行此文件的C预处理器并获取

% cpp linenumber.c
# 1 "linenumber.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "linenumber.c"







("Line"#8"of file""linenumber.c")
("Line " "9" " of file " "linenumber.c")