cmake - 删除使用 link_libraries() 添加的库

标签 cmake

如何删除使用 link_libraries() 添加的库?

是的,我知道我应该使用 target_link_libraries() .我不能,因为我必须将一个库链接到每个 future 的目标。 See this .该库是 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!

在我的例子中,link-to-all 是一个实现了覆盖率检查功能的库。它根据配置选项启用,应该隐式用于所有即将到来的目标。可能会针对特定目标禁用覆盖率分析,因此我希望能够禁用它。

通过在 CMAKE_<LANG>_COMPILE_OBJECT 前加上覆盖启用并通过删除前缀禁用。 Afaik 这不能针对特定目标完成,只能针对即将到来的目标进行全局处理。所以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()

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

最佳答案

虽然我同意@Guillaume,但我会将这些建议合并为一个答案,因为链接的答案不是很清楚。正如@Tsyvarev 确认的那样in the CMake source , link_libraries() 调用设置了 LINK_LIBRARIES目标属性(property); 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}")

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

Libraries linked to e3: link-to-all;link-to-almost-all
Libraries linked to e3: link-to-all

关于cmake - 删除使用 link_libraries() 添加的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58188830/

相关文章:

visual-c++ - 是否可以强制 CMake/MSVC 对没有 BOM 的源文件使用 UTF-8 编码? C4819

cmake - 铿锵 + icecc + ccache

cmake - 为 ROS 编写 CMakeLists.txt

c++ - Cmake 构建失败,CMAKE_AR-NOTFOUND(未找到 cr exe)

c++ - CMake如何选择gcc和g++进行编译?

c++ - 错误 : export ordinal too large: 104116

android - 在不使用 qmake 的情况下在 Android 的 Qt 应用程序上使用自定义 AndroidManifest?

windows - Windows下用MinGW-w64编译POCO库(找不到消息编译器)

c++ - 如何在 cmake 中启用 `/std:c++latest`?

android - Android Studio 项目中的 C++ 代码是否最终出现在 apk 文件中(除了 .so 文件)?