Linking library to library...

Hello,

I am trying to do a hierarchy of static libraries :

Executable → libC → libB → libA

Each target retrieves the used library with FetchContent.
The problem is that target_link_directories() and target_link_libraries() are not recursive.
So, for libC, for exemple, I have to fetch libB and libA. The final client has to know all the dependency hierarchy.

I know it isn’t possible to link a static library to an other static library at the system level, but could CMake, when calling target_link_libraries(libA libB), extract the object files in libA, and put them in libB ?

CMake propagate automatically static libraries to the final target. So;

target_link_libraries(libB libA)
target_link_libraries(libC libB)
add_library(final_lib SHARED libC)

Any final target, like executable or shared library, linking with libC will also link against libB and libA. Just ensure that CMP0099 policy is set to NEW.

And, by the way, if you are using CMake targets, you don’t have to specify any directory. Using target_link_libraries() command is enough.

Well, the problem is the 3 lines of code are made in different CMake projects.

  • project A: builds libA, and puts the libA installation files on a server
  • project B: fetches libA’s content from the server, link it to libB, and puts the libB installation files on a server
  • project C: fetches libA’s content from the server (I’d like avoiding that), fetches libB’s content from the server, link them to libC, and puts the libC installation files on a server
  • project final: fetches libA’s content from the server (I’d like avoiding that), fetches libB’s content from the server (I’d like avoiding that), fetches libC’s content from the server, link them to final_lib, and puts the final_lib installation files on a server

In this case you have to use OBJECT libraries to aggregate all objects in various static libraries.

Very interesting.

But if I take the examples given in the documentation :

add_library(archive OBJECT archive.cpp zip.cpp lzma.cpp)
add_library(archiveExtras STATIC $<TARGET_OBJECTS:archive> extras.cpp)
add_executable(test_exe $<TARGET_OBJECTS:archive> test.cpp)

Does that work if for the first instruction, I set STATIC instead of OBJECT ?
Because the coder of archive cannot know if the client of archive will want to use it to be aggregated to an other library, or to be linked it to an executable.

Also, I am troubled by this sentence :

The link (or archiving) step of those other targets will use the object files from OBJECT libraries that are directly linked.

Why emphasing this “directly”, whereas it is said later there will be a transitive propagation ?