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.
I don't know of a direct way. You could use:
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__
.You can take __FILE__ and the strip off the part of path you don't want (programatically). If basedir satisfies your needs, then fine. Otherwise, get source dir root from your build system, and the rest should be doable.
Taking the idea from Glomek, it can be automated like this:
Source file x.c
Compilation line (beware the single quotes outside the double quotes):
The output is '
abcd.c
'.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:
to:
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:
File src/main.c:
Run from the shell:
Note the "file =" line which contains only the basename of the file, not the dirname.
Could be done ONLY programmatically.
maybe this is useful...
You could use:
Or, you could use NDEBUG in your Macro to turn on/off those file paths.