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
当前回答
编译时没有办法做到这一点。显然,您可以在运行时使用C运行时实现它,正如其他一些答案所演示的那样,但是在编译时,当预处理器启动时,您就不走运了。
其他回答
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__, '/')
GCC 8现在有-fmacro prefix-map和- file-prefix-map选项:
-fmacro-prefix-map = =新老 当预处理位于旧目录下的文件时,展开__FILE__和__BASE_FILE__宏,就好像文件位于新目录下一样。这可用于将绝对路径更改为相对路径。对于new,这可以导致更可重复的构建,这些构建是独立于位置的。该选项还会在编译期间影响__builtin_FILE()。参见- file-prefix-map。
-ffile-prefix-map = =新老 当编译位于旧目录中的文件时,记录所有引用 对他们来说,编译的结果就好像文件就在里面一样 改为新建目录。指定此选项相当于 指定所有单独的-f*-prefix-map选项。可以使用这个 制作独立于位置的可重复构建。另请参阅 -fmacro prefix-map和-fdebug-prefix-map。
为- file-prefix-map (-fdebug-prefix-map)设置无效路径将中断调试,除非你告诉调试器如何映射回去。(gdb: set replace -path, vscode: "sourceFileMap")。
如果你的意图只是清理__FILE__,只需使用-fmacro prefix-map。
例子: 所以对于我的Jenkins构建,我将添加- file-prefix-map=${WORKSPACE}/=/,并删除本地开发包安装前缀。
不幸的是- file-prefix-map和-fmacro prefix-map选项仅在GCC 8以后可用。例如,对于GCC 5,我们只有-fdebug-prefix-map,它不影响__FILE__。
只是希望改进一下FILE宏:
#定义文件(strrchr(__FILE__, '/') ?strrchr __FILE __, '/') + 1: strrchr __FILE __, '\\') ?strrchr(__FILE__, '\\') + 1: __FILE__)
这捕获/和\,像Czarek Tomczak要求的,这在我的混合环境中工作得很好。
在MSVC中,将FILENAME宏作为FILENAME=%(FILENAME)%(扩展名)添加到c++项目的预处理器定义中。恐怕这完全是一个编译器杀手。它在某种程度上打破了并行构建。
一个简短的,适用于Windows和*nix的答案:
#define __FILENAME__ std::max<const char*>(__FILE__,\
std::max(strrchr(__FILE__, '\\')+1, strrchr(__FILE__, '/')+1))