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.
__FILE__ This macro expands to the name of the current input file, in the form of a C string constant. This is the path by which the preprocessor opened the file, not the short name specified in ' #include ' or as the input file name argument. For example, "/usr/local/include/myheader.
The __FILE__ macro expands to a string whose contents are the filename, surrounded by double quotation marks ( " " ). If you change the line number and filename, the compiler ignores the previous values and continues processing with the new values. The #line directive is typically used by program generators.
Header files ( . h ) are designed to provide the information that will be needed in multiple files. Things like class declarations, function prototypes, and enumerations typically go in header files. In a word, "definitions".
An H file is a header file referenced by a document written in C, C++, or Objective-C source code. It may contain variables, constants, and functions that are used by other files within a programming project. H files allow commonly used functions to be written only once and referenced by other source files when needed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With