#include __FILE__:编译器之间的 __FILE__ 值不同:标准怎么说?
#include __FILE__: different __FILE__'s value between compilers: what the standard says?
示例代码(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
结果:
$ 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
编译器版本:
cl: 19.25.28611
gcc: 10.2.0
clang: 11.0.0
问:标准是怎么说的?
C 2018 6.10.8.1 1 说:
The following macro names shall be defined by the implementation:
…
__FILE__
The presumed name of the current source file (a character string literal).
…
由于C标准对__FILE__
没有其他要求,任何作为源文件名的字符串字面量都满足要求。它可以包含或省略任何序列,例如 ./
,只要该字符串是当前源文件的名称即可。
(还有一个注释说可以通过 #line
指令更改假定的源文件名。)
示例代码(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
结果:
$ 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
编译器版本:
cl: 19.25.28611
gcc: 10.2.0
clang: 11.0.0
问:标准是怎么说的?
C 2018 6.10.8.1 1 说:
The following macro names shall be defined by the implementation:
…
__FILE__
The presumed name of the current source file (a character string literal).…
由于C标准对__FILE__
没有其他要求,任何作为源文件名的字符串字面量都满足要求。它可以包含或省略任何序列,例如 ./
,只要该字符串是当前源文件的名称即可。
(还有一个注释说可以通过 #line
指令更改假定的源文件名。)