【问题标题】:How do I access the source file name in CMake?如何在 CMake 中访问源文件名?
【发布时间】:2019-08-02 08:06:14
【问题描述】:

我想使用 CMake 和 Ninja 启用 code analysis

file(GLOB_RECURSE sources *.cpp)

target_sources(${target}
    PRIVATE 
        ${sources}
)

target_compile_options(${target}
    PRIVATE
        -analyze:log report.xml
        -analyze:ruleset "${RuleSet}"
        -analyze:quiet
)

生成的build.ninja大致如下(省略了很多不相关的数据):

build foo.cpp.obj: CXX_COMPILER foo.cpp:
  FLAGS = -analyze:log report.xml -analyze:ruleset "C:\rulesets\MixedRecommendedRules.ruleset" -analyze:quiet

build bar.cpp.obj: CXX_COMPILER bar.cpp
  FLAGS = -analyze:log report.xml -analyze:ruleset "C:\rulesets\MixedRecommendedRules.ruleset" -analyze:quiet

问题在于每个源文件都是单独编译的,因此每次调用编译器时报告都会被覆盖

有没有办法像这样包含源文件名

target_compile_options(${target}
    PRIVATE
        -analyze:log report_{source_file}.xml
        -analyze:ruleset "${RuleSet}"
        -analyze:quiet
)

【问题讨论】:

标签: c++ cmake ninja


【解决方案1】:

我关注了这个suggestion,最终得到了以下结果:

file(GLOB_RECURSE sources *.cpp)

target_sources(${target}
    PRIVATE 
        ${sources}
)

foreach(source_file ${sources})
    get_filename_component(file_name ${source_file} NAME)
    set_source_files_properties(${source_file} PROPERTIES COMPILE_OPTIONS "-analyze:log ${file_name}_report.xml")
endforeach()

target_compile_options(${target}
    PRIVATE
        -analyze:ruleset "${RuleSet}"
        -analyze:quiet
)

【讨论】:

    【解决方案2】:

    你可以做的是像这样从文件中获取文件名组件;

    foreach (_src_file ${source})
      get_filename_component(_src_filename ${_src_file} NAME)
      target_compile_options(${target}
        PRIVATE
            -analyze:log report_${_src_filename}.xml
            -analyze:ruleset "${RuleSet}"
            -analyze:quiet
      )
    endforeach()
    

    主要缺点是您需要单独检查每个文件,并且不能像上面的示例那样将其作为列表进行。

    也许还有其他选项可以满足您的需求,请查看the get_filename_component documentation.

    【讨论】:

    • 我试过了,但是在 build.ninja 文件中,target_compile_options 部分中指定的所有编译器标志都丢失了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2017-07-20
    • 2015-09-11
    • 2011-01-24
    • 2011-04-01
    相关资源
    最近更新 更多