Is there a specification on how the __FILE__
macro will be expanded if it is in a .h
?
If I define in foo.h
#define MYFILE __FILE__
And include it in foo.c
#include "foo.h"
int main(){
printf("%s",MYFILE);
....
}
Does this output foo.h
or foo.c
? (Yes I realize this is a stupid example)
Sorry for what should be a simple question. The documentation 开发者_StackOverflowon the web seems conflicting. For what it is worth VS2008 comes back as foo.c
which is what I would expect....I think. I am just trying to confirm if this is defined behavior.
The advice given in yan's answer is 'generally correct'. That is, the value of __FILE__
is the name of the current source file when the macro is used, not when the macro is defined. However, it is not absolutely correct - and here is a counter-example:
$ cat x.h
static void helper(void)
{
printf("%s:%d helper\n", __FILE__, __LINE__);
}
$ cat x.c
#include <stdio.h>
#include "x.h"
int main(void)
{
helper();
printf("%s:%d\n", __FILE__, __LINE__);
return 0;
}
$ make x
cc -Wall -Wextra -std=c99 -g x.c -o x
$ ./x
x.h:3 helper
x.c:7
$
This is a contrived example; in C, you very seldom put actual code into a header as I did here — unless you are using inline
functions. But the output shows that there are circumstances where the name of the header can be the correct name that __FILE__
expands to.
It will always return the .c where it's used, as __LINE__
and __FILE__
are resolved after the pre-processor. This way, you can write debug macros that use __FILE__
and __LINE__
and have them point to where the debug statements appear.
Macro expansion (of all macros, not just special ones like __FILE__
) is done after #include
substitution, so yes, this behaviour can be relied upon.
The actual language in the standard is (§6.10.8):
__FILE__
The presumed name of the current source file (a character string literal).
Because macro expansion happens after #include
s are processed, the "current source file" is the preprocessed .c file being compiled.
That #define macro does literal text replacement pre-compilation. By the time the C compiler hits your foo.c file, it sees:
printf("%s", __FILE__);
so you're getting foo.c.
精彩评论