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.
If you’re using a
makeprogram, you should be able to munge the filename beforehand and pass it as a macro togccto be used in your program. For example, in yourmakefile, change the line:to:
This will allow you to use
MYFILEin your code instead of__FILE__.The use of
basenameof the source file$<means you can use it in generalized rules such as.c.o. The following code illustrates how it works. First, amakefile:Then a file in a subdirectory,
src/main.c:Finally, a transcript showing it running:
Note the
file =line which contains only the base name of the file, not the directory name as well.