【问题标题】:In CMake, specify all executables target_link_libraries certain libraries在 CMake 中,指定所有可执行文件 target_link_libraries 某些库
【发布时间】:2012-05-11 17:06:26
【问题描述】:

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

【问题讨论】:

    标签: c++ c cmake


    【解决方案1】:

    你可以用你自己的覆盖内置的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()
    

    【讨论】:

    • 我不知道您可以覆盖内置命令。很高兴知道。
    • 我刚刚在tcmalloc 文档中读到它必须位于链接器列表的末尾,并且仅使用target_link_libraries 指定依赖项并不能保证该条件.如果不在链接列表的末尾,则会出现错误的泄漏报告。
    【解决方案2】:

    您可以在 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)
    

    查看the documentation了解更多信息。

    【讨论】:

    • 它有效,但有点老套。我需要用setup 替换每个add_executable。是否有一些我可以全局设置的变量来实现这一点?
    • 您可以修改 CMAKE_EXE_LINKER_FLAGS 变量(检查构建目录中的 CMakeCache.txt)。就我个人而言,我会说这更像是一种 hack,而不是切换到一个函数,但如果你的项目中有大量可执行文件,那就是更快的解决方案。
    猜你喜欢
    • 2014-01-24
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2012-01-26
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多