Why my macro doesn't compile?

166 views Asked by At
#define LINE_FILE ("Line"#__LINE__"of file"__FILE__)

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

What I expected:

LINE_FILE = "Line linenumber of file filename"

and printf() can output this string.

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

4

There are 4 answers

0
Toni Homedes i Saun On

AFAIK you can not do that on the preprocessor, the usual way is:

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

You need an stringify helper

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

then

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

__LINE__ does no expand to a "string", but to an int.

To get around this you might like to do the following:

#define _LINE_FILE2(filename, linenumber) "Line " #linenumber " of " filename 
#define _LINE_FILE1(filename, linenumber) _LINE_FILE2(filename, linenumber)
#define LINE_FILE _LINE_FILE1(__FILE__, __LINE__)

Further (gcc) details on

0
lollo On

To debug the macro you may use the C preprocessor separate.

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

Run the C preprocessor for this file and get

% 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")