首页 > 解决方案 > 以编程方式获取 CMake 项目中的所有目标

问题描述

我想让一个特定的目标依赖于我项目中所有其他添加的目标。换一种说法——我希望这个目标(比如lint)在所有库和应用程序构建完成后运行。

CMakeLists.txt在指定 的顶部文件中是否有办法获取使用添加的目录中其他文件project添加的所有目标的列表?然后我可以使用来指定顺序。有一个属性,但它仅适用于目录级别。CMakeLists.txtadd_subdirectoryadd_dependenciesBUILDSYSTEM_TARGETS

如果有其他方法可以实现这一点,请告诉我。我使用 CMake 3.14。

标签: cmake

解决方案


为了将来的参考,我最终编写了自己的函数而不是宏。但这个概念与@thomas_f 接受的答案相同。

这是代码:

# Collect all currently added targets in all subdirectories
#
# Parameters:
# - _result the list containing all found targets
# - _dir root directory to start looking from
function(get_all_targets _result _dir)
    get_property(_subdirs DIRECTORY "${_dir}" PROPERTY SUBDIRECTORIES)
    foreach(_subdir IN LISTS _subdirs)
        get_all_targets(${_result} "${_subdir}")
    endforeach()

    get_directory_property(_sub_targets DIRECTORY "${_dir}" BUILDSYSTEM_TARGETS)
    set(${_result} ${${_result}} ${_sub_targets} PARENT_SCOPE)
endfunction()

推荐阅读