删除使用 link_libraries() 添加的库

kug*_*uga 3 cmake

如何删除添加的库link_libraries()

是的,我知道我应该使用target_link_libraries(). 我不能,因为我必须将一个库链接到每个未来的目标。看到这个。该库是 CMake 构建的。这对于 C++/CMake 开发人员来说应该是不可见的。他不应该担心这个库。例子:

add_library(link-to-all a.cpp)
link_libraries(link-to-all)
add_executable(e1 e1.cpp) # with link-to-all
add_executable(e2 e2.cpp) # with link-to-all
unlink_libraries(link-to-all) #does not exist!
add_executable(e3 e3.cpp) # without link-to-all
# all further targets link without link-to-all!
Run Code Online (Sandbox Code Playgroud)

就我而言,link-toall 是一个实现覆盖率检查功能的库。它的启用取决于配置选项,并且应该隐式地用于所有即将到来的目标。可能会针对特定目标禁用覆盖率分析,因此我希望能够禁用它。

通过添加前缀来启用覆盖范围CMAKE_<LANG>_COMPILE_OBJECT,通过删除前缀来禁用覆盖范围。据我所知,这不能针对特定目标来完成,只能针对即将到来的目标进行全局。所以这unlink_libraries()将是一个我可以对称调用的函数。

function(enable_coverage)
   prepend_compiler();
   link_libraries(cov);
   # alternative with loosing target information/dependency
   # prepend_system_libs(<path>/libcov.a)
endfunction()
function(disable_coverage)
   reset_compiler();
   unlink_libraries(cov);
   # reset_system_libs()
endfunction()
Run Code Online (Sandbox Code Playgroud)

我可以使用CMAKE_<LANG>_STANDARD_LIBRARIES, (也可以在那里删除它),但我需要那里LOCATION的库(生成器表达式:) 。TARGET但我也会失去link-to-all. 此外,这可能会删除构建依赖项。

squ*_*les 5

虽然我同意@Guillaume,但我会将这些建议合并为答案,因为链接的答案不是很清楚。正如 @Tsyvarev在 CMake 源代码中确认的那样,link_libraries()调用设置了LINK_LIBRARIES目标属性;调用target_link_libraries()的作用相同。虽然您的可执行文件e3最初将设置为与所有库链接,但您可以使用get_target_property()和的组合从列表中删除一个(或多个)库set_property()。下面是一个演示如何操作的示例:

# Library to be linked to all targets.
add_library(link-to-all a.cpp)
# Library to be linked to (almost) all targets.
add_library(link-to-almost-all b.cpp)

link_libraries(link-to-all link-to-almost-all)
# Gets our link-everywhere libraries. Oops!
add_executable(e3 test.cpp)

# Get the LINK_LIBRARIES property for this target.
get_target_property(E3_LINKED_LIBS e3 LINK_LIBRARIES)
message("Libraries linked to e3: ${E3_LINKED_LIBS}")

# Remove one item from the list, and overwrite the previous LINK_LIBRARIES property for e3.
list(REMOVE_ITEM E3_LINKED_LIBS link-to-almost-all)
set_property(TARGET e3 PROPERTY LINK_LIBRARIES ${E3_LINKED_LIBS})

# Verify only one library is now linked.
get_target_property(E3_LINKED_LIBS_NEW e3 LINK_LIBRARIES)
message("Libraries linked to e3: ${E3_LINKED_LIBS_NEW}")
Run Code Online (Sandbox Code Playgroud)

此处打印的消息确认库已从LINK_LIBRARIES目标属性中删除e3

Libraries linked to e3: link-to-all;link-to-almost-all
Libraries linked to e3: link-to-all
Run Code Online (Sandbox Code Playgroud)