Getting base name of the source file at compile time

后端 未结 14 2292
有刺的猬
有刺的猬 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:31

    It is easy with cmake.

    DefineRelativeFilePaths.cmake

    function (cmake_define_relative_file_paths SOURCES)
      foreach (SOURCE IN LISTS SOURCES)
        file (
          RELATIVE_PATH RELATIVE_SOURCE_PATH
          ${PROJECT_SOURCE_DIR} ${SOURCE}
        )
    
        set_source_files_properties (
          ${SOURCE} PROPERTIES
          COMPILE_DEFINITIONS __RELATIVE_FILE_PATH__="${RELATIVE_SOURCE_PATH}"
        )
      endforeach ()
    endfunction ()
    

    Somewhere in CMakeLists.txt

    set (SOURCES ${SOURCES}
      "${CMAKE_CURRENT_SOURCE_DIR}/common.c"
      "${CMAKE_CURRENT_SOURCE_DIR}/main.c"
    )
    
    include (DefineRelativeFilePaths)
    cmake_define_relative_file_paths ("${SOURCES}")
    

    cmake .. && make clean && make VERBOSE=1

    cc ... -D__RELATIVE_FILE_PATH__="src/main.c" ... -c src/main.c
    

    That's it. Now you can make pretty log messages.

    #define ..._LOG_HEADER(target) \
      fprintf(target, "%s %s:%u - ", __func__, __RELATIVE_FILE_PATH__, __LINE__);
    

    func src/main.c:22 - my error

    PS It is better to declear in config.h.in -> config.h

    #ifndef __RELATIVE_FILE_PATH__
    #define __RELATIVE_FILE_PATH__ __FILE__
    #endif
    

    So your linter wan't provide rain of errors.

提交回复
热议问题