C语言中可用的标准预定义宏__FILE__显示文件的完整路径。有办法缩短这条路吗?我的意思是
/full/path/to/file.c
我看到
to/file.c
or
file.c
C语言中可用的标准预定义宏__FILE__显示文件的完整路径。有办法缩短这条路吗?我的意思是
/full/path/to/file.c
我看到
to/file.c
or
file.c
当前回答
Try
#pragma push_macro("__FILE__")
#define __FILE__ "foobar.c"
在源文件中的include语句之后,然后添加
#pragma pop_macro("__FILE__")
在源文件的末尾。
其他回答
因为使用的是GCC,所以可以利用
__BASE_FILE__这个宏扩展为主输入文件的名称,以C字符串常量的形式。这是源文件 在预处理器或C编译器的命令行中指定
然后在编译时通过更改源文件表示(完整路径/相对路径/basename)来控制显示文件名的方式。
Try
#pragma push_macro("__FILE__")
#define __FILE__ "foobar.c"
在源文件中的include语句之后,然后添加
#pragma pop_macro("__FILE__")
在源文件的末尾。
最近的Clang编译器有一个__FILE_NAME__宏(见这里)。
I think this is better than using strrchr function. strfnchr will search last delemeter '/' and get filename from __FILE__ and you can use __FILE__NAME__ instead __FILE__ for get file name without full file path. strrchr solution searching filename twice per use. but this code is just 1 time search. And it works effectively even if there is no seperater '/' in __FILE__. You can use it by replacing it with \ as needed. The source code of strfnchr was improved by using the source code of strrchr below. I think it will work more effectively than strrchr. https://code.woboq.org/userspace/glibc/string/strrchr.c.html
inline const char* strfnchr(const char* s, int c) {
const char* found = s;
while (*(s++)) {
if (*s == c)
found = s;
}
if (found != s)
return found + 1;
return s;
}
#define __FILE_NAME__ strfnchr(__FILE__, '/')
如果您最终在本页上寻找一种方法,以从您正在交付的二进制文件中删除指向丑陋构建位置的绝对源路径,那么下面可能适合您的需要。
尽管这并没有得到作者所希望的答案,因为它假设使用CMake,但它已经非常接近了。很遗憾之前没有人提到这一点,因为这可以节省我很多时间。
OPTION(CMAKE_USE_RELATIVE_PATHS "If true, cmake will use relative paths" ON)
将上述变量设置为ON将生成如下格式的构建命令:
cd /ugly/absolute/path/to/project/build/src &&
gcc <.. other flags ..> -c ../../src/path/to/source.c
因此,__FILE__宏将解析为../../src/path/to/source.c
CMake文档
但是要注意文档页上的警告:
使用相对路径(可能不起作用!)
它不能保证在所有情况下都能工作,但在我的CMake 3.13 + gcc 4.5中工作