Abhishek Arya
Abhishek Arya

Reputation: 500

What happens with target_link_libraries(libstatic libfoo libbar)?

I am bit confused about linking libraries when our target is a static library.

For instance, for an executable it will help linker resolve undefined symbols. But, incase of a static libraries, why would it link at this stage?

Won't linking be done when I will link some executable against libstatic?

Thanks.

Upvotes: 0

Views: 69

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 66081

In CMake,

target_link_libraries(targetName PUBLIC lib1 lib2)

affects to the linker's argument in two scenarios:

  1. PRIVATE: when the linker is called for the for the executable/library, corresponded to the target targetName.
  2. INTERFACE: when the linker is called for the other executable/library otherTargetName, which is linked with targetName via

    target_link_libraries(otherTargetName PUBLIC targetName)
    

    This is known as transitive property of the linking libraries.

You are right that the linker is not called for the static libraries, so in that case the first scenario is eliminated.

But the second scenario remains: When you create the executable (or other shared library) and call

target_link_libraries(otherTargetName PUBLIC libStatic)

then CMake automatically links that executable(or shared library) with everything, to which libStatic is "linked" with target_link_libraries.


Such automation helps in structuring the project:

  1. By calling

    target_link_libraries(libStatic PUBLIC lib1 lib2)
    

    you state, that libStatic uses functions defined in lib1 and lib2

  2. By calling

    target_link_libraries(otherTargetName PUBLIC libStatic)
    

    you state, that executable/library otherTargetName uses functions from libStatic.

    At this stage you don't care about internals of libStatic, whether it is self-contained or depends from some other libraries: CMake will care about this for you.


Note on using PUBLIC keyword in target_link_libraries: while in some cases this is equivalent to omitting the keyword, a modern CMake way is to specify keywords explicitly. See also policy CMP0023.

Other possible keywords are PRIVATE and INTERFACE, each of them selects only a single scenario described above.


Note that transitive linking property is a pure CMake feature and works only when linking to a target. The library file (.a or .lib) itself doesn't contain information about dependent libraries, so linking with a file doesn't trigger transitive linking.

Upvotes: 2

Related Questions