学习源$ C $ C的在编译时的文件名 [英] Learning the source code's filename at compile time
问题描述
我使用GCC我; __FILE__返回当前源文件的完整路径和名称。有没有办法得到的只是文件的名称,而不是它的整个路径太(在编译时)?是否有可能做到这一点的可移植的方法?可模板元编程应用到字符串?
I'm using GCC; __FILE__ returns the current source file's entire path and name. Is there a way to get just the file's name and not its whole path too (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程序,你应该能够事先munge的文件名,并把它作为一个宏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
这将让你在你的code,而不是使用
。 __ MYFILE __
__ FILE __
This will allow you to use __MYFILE__
in your code instead of __FILE__
.
使用源文件的基本名的($&LT)是指你可以用它在通用规则,如.c.o
The use of basename of the source file ($<) means you can use it in generalized rules such as ".c.o".
以下code说明它是如何工作的。
The following code illustrates how it works.
的 Makefile文件:的
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;
}
的从shell中运行:的
pax@pax-desktop:~$ mainprog
file = main.c
pax@pax-desktop:~$
请注意这仅包含文件,而不是目录名的基本名称的文件=行。
Note the "file =" line which contains only the basename of the file, not the dirname.
这篇关于学习源$ C $ C的在编译时的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!