Getting base name of the source file at compile time

后端 未结 14 2310
有刺的猬
有刺的猬 2020-12-14 10:07

I\'m using GCC; __FILE__ returns the current source file\'s entire path and name: /path/to/file.cpp. Is there a way to get just the file\'s name file.cpp<

14条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 10:30

    Since you tagged CMake, here's a neat solution to add to your CMakeLists.txt: (copied from http://www.cmake.org/pipermail/cmake/2011-December/048281.html ). (Note : some compilers don't support per-file COMPILE_DEFINITIONS ! but it works with gcc)

    set(SRCS a/a.cpp b/b.cpp c/c.cpp d/d.cpp)
    
    foreach(f IN LISTS SRCS)
     get_filename_component(b ${f} NAME)
     set_source_files_properties(${f} PROPERTIES
      COMPILE_DEFINITIONS "MYSRCNAME=${b}")
    endforeach()
    
    add_executable(foo ${SRCS})
    

    Note : For my application I needed to escape the filename string like this:

    COMPILE_DEFINITIONS "MYSRCNAME=\"${b}\"")
    

提交回复
热议问题