Getting base name of the source file at compile time
I don't know of a direct way. You could use:
#line 1 "filename.c"
at the top of the source file to set the value of __FILE__
, but I'm not sure that that's much better than hard coding it. or just using a #define to create your own macro.
Another option might be to pass the name from your Makefile using -D and $(shell basename $<)
Edit: If you use a #define or the -D option, you should create your own new name and not try to redefine __FILE__
.
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\n", 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.