Rolle Rolle - 10 months ago 59
C++ Question

Why does cmake_link_libraries include static libs?

I want my executable to link agains a shared library (, that in turn is built with a static library (libmy_static_lib.a). When I do

target_link_libraries(my_exe my_so)

I see when compiling that cmake had added libmy_static_lib.a on the build line. This is not something I want and I dont understand why this is needed. Is there any way around this?
does not seem to make any difference.

I use CMake 2.8.9.

Answer Source

From the 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.

The solution is to use the signature of target_link_libraries that allows to specify transitive behavior manually:

# 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)