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.
Compiler Services Allows you to obtain the full path of the source file that contains the caller. This is the file path at the time of compile. The following example shows how to use the CallerFilePath attribute. On each call to the TraceMessage method, the caller information is substituted as an argument to the optional parameter.
Or, if you know the filename extension and want to get the first part of the filename — the base filename, the part before the extension — you can also use basename like this: I was just working on a little Unix shell script, and wrote this code to loop over a bunch of LaTeX files in the current directory:
You obtain the file path of the source code, the line number in the source code, and the member name of the caller. To obtain member caller information, you use attributes that are applied to optional parameters.
As a quick note today, if you’re ever writing a Linux shell script and need to get the filename from a complete (canonical) directory/file path, you can use the Linux basename command like this: $ basename /foo/bar/baz/foo.txt foo.txt.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With