在编译时获取源文件的基本名称 [英] Getting base name of the source file at compile time
问题描述
我正在使用GCC; __FILE__返回当前源文件的完整路径和名称:/path/to/file.cpp
.有没有一种方法可以在编译时仅获取文件名file.cpp
(不包含其路径)?是否可以通过便携式方式执行此操作?模板元编程可以应用于字符串吗?
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.
推荐答案
如果使用的是make程序,则应该能够预先修改文件名,并将其作为宏传递给gcc,以在程序中使用.
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.
在您的makefile中,更改以下行:
In your makefile, change the line:
file.o: file.c
gcc -c -o file.o src/file.c
收件人:
file.o: src/file.c
gcc "-D__MYFILE__=\"`basename $<`\"" -c -o file.o src/file.c
这将允许您在代码中使用__MYFILE__
而不是__FILE__
.
This will allow you to use __MYFILE__
in your code instead of __FILE__
.
使用源文件的基本名称($<)意味着您可以在诸如".c.o"之类的通用规则中使用它.
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.
文件制作文件:
mainprog: main.o makefile
gcc -o mainprog main.o
main.o: src/main.c makefile
gcc "-D__MYFILE__=\"`basename $<`\"" -c -o main.o src/main.c
文件src/main.c:
#include <stdio.h>
int main (int argc, char *argv[]) {
printf ("file = %s\n", __MYFILE__);
return 0;
}
从外壳运行:
pax@pax-desktop:~$ mainprog
file = main.c
pax@pax-desktop:~$
请注意"file =行,其中仅包含文件的基本名称,而不包含目录名称.
Note the "file =" line which contains only the basename of the file, not the dirname.
这篇关于在编译时获取源文件的基本名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!