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
当前回答
如果你使用CMAKE和GNU编译器,这个全局定义工作正常:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__MY_FILE__='\"$(notdir $(abspath $<))\"'")
其他回答
使用basename()函数,或者,如果是在Windows上,使用_splitpath()。
#include <libgen.h>
#define PRINTFILE() { char buf[] = __FILE__; printf("Filename: %s\n", basename(buf)); }
还可以在shell中尝试man 3 basename。
对于Visual Studio,您可以使用/d1trimfile选项。
你可能想把它设置为/d1trimfile:"$(SolutionDir)\":
注意:“”前面加了\的解释:
要转义第一个($(SolutionDir)以反斜杠结束),否则将转义引号。你需要等量的反斜杠 在引用之前。
Try
#pragma push_macro("__FILE__")
#define __FILE__ "foobar.c"
在源文件中的include语句之后,然后添加
#pragma pop_macro("__FILE__")
在源文件的末尾。
下面是使用编译时计算的解决方案:
constexpr auto* getFileName(const char* const path)
{
const auto* startPosition = path;
for (const auto* currentCharacter = path;*currentCharacter != '\0'; ++currentCharacter)
{
if (*currentCharacter == '\\' || *currentCharacter == '/')
{
startPosition = currentCharacter;
}
}
if (startPosition != path)
{
++startPosition;
}
return startPosition;
}
std::cout << getFileName(__FILE__);
如果你使用CMAKE和GNU编译器,这个全局定义工作正常:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__MY_FILE__='\"$(notdir $(abspath $<))\"'")