有运行时解决办法,把 __FILE__结果裁剪一下,太弱智了

#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)

见参考链接,居然还采纳了你敢信??

正确的编译期做法是第二个答案

如果是cmake

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__FILENAME__='\"$(subst  ${CMAKE_SOURCE_DIR}/,,$(abspath $<))\"'")

另外@houjw-hx 提到notdir,更清爽,在此补充表示感谢

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__FILENAME__='"$(notdir $<)"'")

确实简单一些。不太了解cmake这些小接口,我都是搜到能对付用的就直接用了。。

如果是makefile

CXX_FLAGS+=-D__FILENAME__='\"$(subst $(SOURCE_PREFIX)/,,$(abspath $<))\"'"

然后把__FILE__替换成__FILENAME__或者把上面的__FILENAME__替换成__FILE__

可能会有告警,但是无关紧要

但是如果设置了-Werror可能会编译不过,需要设定-Wno-builtin-macro-redefined

cmake

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-builtin-macro-redefined")

不然会有<command line>:41:9: error: redefining builtin macro [-Werror,-Wbuiltin-macro-redefined] 编译错误


ref

  1. https://stackoverflow.com/questions/8487986/file-macro-shows-full-path/16658858# 第一个答案是运行时裁剪,第二个答案更好。
  2. https://public.kitware.com/pipermail/cmake/2013-January/053117.html cmake做法
  3. https://blog.csdn.net/huojianying123456/article/details/70176755 makefile做法
  4. https://blog.csdn.net/yindongjie1221/article/details/90614261 这个写了一大堆,太复杂了。没用
  5. https://stackoverflow.com/questions/53182242/how-to-override-the-value-of-time-and-date-macros-using-command-line-opt 告警处理方法