为什么 cmake_link_libraries 包含静态库?

Why does cmake_link_libraries include static libs?

我希望我的可执行文件再次 link 共享库 (libmy_so.so),而共享库又是用静态库 (libmy_static_lib.a) 构建的。当我这样做时

target_link_libraries(my_exe my_so)

我在编译时看到 cmake 在构建行上添加了 libmy_static_lib.a。这不是我想要的,我不明白为什么需要这样做。有没有办法解决? LINK_PRIVATE 好像没什么区别。

我使用 CMake 2.8.9.

来自CMake documentation for target_link_libraries

target_link_libraries(<target> [item1 [item2 [...]]]
                      [[debug|optimized|general] <item>] ...)

[...] Library dependencies are transitive by default with this signature. When this target is linked into another target then the libraries linked to this target will appear on the link line for the other target too.

解决方案是使用 target_link_libraries 的签名,允许手动指定传递行为:

# we explicitly state that the static lib should not propagate
# transitively to targets depending on my_so
target_link_libraries(my_so PRIVATE my_static_lib)

# nothing has to change for the exe
target_link_libraries(my_exe my_so)