c++cgccmakefilemacros

Getting base name of the source file at compile time


I'm using GCC; __FILE__ returns the current source file's entire path and name: /path/to/file.cpp. Is there a way to get just the file's name file.cpp (without its path) at compile time? Is it possible to do this in a portable way? Can template meta programming be applied to strings?

I am using this in an error logging macro. I really do not want my source's full path making its way into the executable.


Solution

  • 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.