Pablitorun
Pablitorun

Reputation: 1025

__FILE__ In .h what does it resolve to

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 on 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.

Upvotes: 14

Views: 6841

Answers (5)

Jonathan Leffler
Jonathan Leffler

Reputation: 754520

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.

Upvotes: 10

Stephen Canon
Stephen Canon

Reputation: 106247

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 #includes are processed, the "current source file" is the preprocessed .c file being compiled.

Upvotes: 4

charleyc
charleyc

Reputation: 1709

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.

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

Macro expansion (of all macros, not just special ones like __FILE__) is done after #include substitution, so yes, this behaviour can be relied upon.

Upvotes: 5

yan
yan

Reputation: 20992

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.

Upvotes: 9

Related Questions