Olumide
Olumide

Reputation: 5809

Specifying target_link_libraries when building shared object in cmake

My project creates a shared object A that 'depends' should reference other shared objects B, C , D and E. After building the project and checking the build with the utility ldd I see no references to the shared objects B, C , D and E. However when I use the directive target_link_libraries(A , B , C , D , E ) in my build the references to the shared objects appear in A.so. My question is two fold:

  1. Is it correct to use target_link_libraries in this way?
  2. If so, why is this use of target_link_libraries correct considering that I'm building a shared object where linking is at runtime.

Example:

My Frobnigator project depends on a ContinuumTransfunctioner and Transmogrifier shared objects that have already been built. My question is about whether the line target_link_libraries(Frobnigator ${Libraries}) is necessary.

cmake_minimum_required(VERSION 3.0)

set(Libraries
    ContinuumTransfunctioner
    Transmogrifier
)

set(SourceFiles
    Wrapper.cpp
    Logger.cpp
)

add_library(Frobnigator SHARED ${SourceFiles})
add_library(FrobnigatorStatic STATIC ${SourceFiles})
set_target_properties(FrobnigatorStatic PROPERTIES OUTPUT_NAME Frobnigator)
#target_link_libraries(Frobnigator ${Libraries}) # Do I need this?

Upvotes: 1

Views: 813

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 65860

Yes, you need to use target_link_libraries even when create SHARED library.

While some symbol resolution is performed at runtime (loading time), there some things which should be performed at build time (linking).

The main thing is ... providing a list of libraries, which should be loading with your library. This list is "embedded" into the library file. There is no other way for dynamic loader to know, which other libraries should be loaded with your one.

Among other things performed at link time is:

  • Checking that all symbols needed for your library are actually available in other libraries.

Upvotes: 2

Related Questions