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.
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 "-D__MYFILE__=\"`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.
File makefile:
mainprog: main.o makefile
gcc -o mainprog main.o
main.o: src/main.c makefile
gcc "-D__MYFILE__=\"`basename $<`\"" -c -o main.o src/main.c
File src/main.c:
#include <stdio.h>
int main (int argc, char *argv[]) {
printf ("file = %s\n", __MYFILE__);
return 0;
}
Run from the shell:
pax@pax-desktop:~$ mainprog
file = main.c
pax@pax-desktop:~$
Note the "file =" line which contains only the basename of the file, not the dirname.