If you're using a make
program, you should be able to munge the filename beforehand and pass it as a macro to gcc
to be used in your program. For example, in your makefile
, change the line:
file.o: file.c
gcc -c -o file.o src/file.c
to:
file.o: src/file.c
gcc "-DMYFILE="`basename $<`"" -c -o file.o src/file.c
This will allow you to use MYFILE
in your code instead of __FILE__
.
The use of basename
of the source file $<
means you can use it in generalized rules such as .c.o
. The following code illustrates how it works. First, a makefile
:
mainprog: main.o makefile
gcc -o mainprog main.o
main.o: src/main.c makefile
gcc "-DMYFILE="`basename $<`"" -c -o main.o src/main.c
Then a file in a subdirectory, src/main.c
:
#include <stdio.h>
int main (int argc, char *argv[]) {
printf ("file = %s
", MYFILE);
return 0;
}
Finally, a transcript showing it running:
pax:~$ mainprog
file = main.c
Note the file =
line which contains only the base name of the file, not the directory name as well.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…