Search code examples
crecursionincludec-preprocessor

#include __FILE__: different __FILE__'s value between compilers: what the standard says?


Sample code (t1.c):

#if defined(M1)
    printf("%s\n", __FILE__);
#undef  M1
#elif   defined(M2)
#define M1
#include __FILE__
#undef  M2
#else
#include <stdio.h>
int main    ( void )
{
    printf("%s\n", __FILE__);
#define M1
#include __FILE__
#define M2
#include __FILE__
    return 0;
}
#endif

Results:

$ gcc t1.c && ./a.exe
t1.c
t1.c
t1.c

$ clang t1.c && ./a.exe
t1.c
./t1.c
./././t1.c

cl t1.c && tc1
t1.c
d:\TEMP\t1.c
d:\TEMP\t1.c

Compiler versions:

cl: 19.25.28611
gcc: 10.2.0
clang: 11.0.0

Question: What does the standard say?


Solution

  • C 2018 6.10.8.1 1 says:

    The following macro names shall be defined by the implementation:

    __FILE__ The presumed name of the current source file (a character string literal).

    As the C standard specifies no other requirements for __FILE__, any string literal that serves as the name of the source file satisfies the requirement. It may contain or omit any sequences such as ./ as long as the string is a name for the current source file.

    (There is also a note that says the presumed source file name can be changed by the #line directive.)