daixtrose / cplusplus-primer

A short introduction to C++ which was quickly hacked together
MIT License
0 stars 0 forks source link

Show CMake trick for including a static library into another another library #5

Open daixtrose opened 2 months ago

daixtrose commented 2 months ago

https://cmake.org/cmake/help/v3.24/manual/cmake-generator-expressions.7.html#genex:LINK_LIBRARY

add_library(lib1 STATIC ...)
add_library(lib2 ...)
target_link_libraries(lib2 PRIVATE "$<LINK_LIBRARY:WHOLE_ARCHIVE,lib1>")
daixtrose commented 2 months ago

One may also check https://cmake.org/cmake/help/latest/prop_tgt/LINK_LIBRARIES_ONLY_TARGETS.html

In order to link toolchain-provided libraries by name while still enforcing LINK_LIBRARIES_ONLY_TARGETS, use an [imported(https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#imported-targets) Interface Library with the IMPORTED_LIBNAME target property:

add_library(toolchain::m INTERFACE IMPORTED)
set_property(TARGET toolchain::m PROPERTY IMPORTED_LIBNAME "m")
target_link_libraries(myExe PRIVATE toolchain::m)
daixtrose commented 2 months ago

very important. https://cmake.org/cmake/help/latest/variable/CMAKE_LINK_LIBRARY_USING_FEATURE.html#loading-a-whole-static-library

A common need is to prevent the linker from discarding any symbols from a static library. Different linkers use different syntax for achieving this. The following example shows how this may be implemented for some linkers.

daixtrose commented 2 months ago

https://inhzus.io/posts/2023-12-01-cmake-external-project/