Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...