在 CMake 中,指定某些库target_link_libraries的所有可执行文件

In CMake, specify all executables target_link_libraries certain libraries

本文关键字:libraries link 可执行文件 target CMake      更新时间:2023-10-16

在CMake中,有没有办法指定我所有的可执行文件都链接到某个库? 基本上,我希望我所有的可执行文件都链接到tcmalloc和分析器。 简单地指定 -ltcmalloc 和 -lprofiler 不是一个好的解决方案,因为我想让 CMake 以可移植的方式找到库的路径。

您可以使用自己的函数覆盖内置的 add_executable 函数,该函数始终添加所需的链接依赖项:

macro (add_executable _name)
    # invoke built-in add_executable
    _add_executable(${ARGV})
    if (TARGET ${_name})
        target_link_libraries(${_name} tcmalloc profiler)
    endif()
endmacro()

您可以在 CMake 中编写一个函数/宏来为您完成工作。

function(setup name sources
add_executable(name sources)
target_link_library(name tcmalloc profiler)
endfunction(setup)
setup(foo foo.c)
setup(bar bar.c)

有关详细信息,请查看文档。