Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 912
Pablitorun Avatar asked Feb 18 '11 23:02

Pablitorun


People also ask

What does __ file __ mean in C?

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

What is __ file __ in C++?

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.

What typically goes into a .h file?

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

What does a .h file do?

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.


1 Answers

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.

like image 67
Jonathan Leffler Avatar answered Sep 24 '22 01:09

Jonathan Leffler