【发布时间】:2012-05-11 17:06:26
【问题描述】:
在 CMake 中,有没有办法指定我的所有可执行文件都链接到某个库?基本上我希望我的所有可执行文件都链接到 tcmalloc 和分析器。简单地指定 -ltcmalloc 和 -lprofiler 不是一个好的解决方案,因为我想让 CMake 以可移植的方式找到库的路径。
【问题讨论】:
在 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()
【讨论】:
tcmalloc 文档中读到它必须位于链接器列表的末尾,并且仅使用target_link_libraries 指定依赖项并不能保证该条件.如果不在链接列表的末尾,则会出现错误的泄漏报告。
您可以在 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。是否有一些我可以全局设置的变量来实现这一点?