No way to apply flags to single static imported library
We have a multi-project cmake setup that includes some IMPORTED
static libraries. For one of our executables we need to force-link in all symbols in a few of these IMPORTED
libraries so we need to pass -Wl,-force_load
to the compiler before the name of that library. Note that there are dependencies between these imported libraries so they need to be placed in the correct order in the link command line. These dependencies are declared in the root CMakeLists.txt
via set_target_properties(fake_2 PROPERTIES INTERFACE_LINK_LIBRARIES ...)
.
We were using the fairly standard target_link_libraries(lib_a PUBLIC -Wl,-force_load fake_4)
but it turns out that cmake treats -Wl,-force_load
as a fairly arbitrary linker flag and if you apply it to several libraries like:
target_link_libraries(lib_a PUBLIC -Wl,-force_load fake_4)
target_link_libraries(lib_a PUBLIC -Wl,-force_load fake_3)
it won't necessary apply those linker flags to both fake_4
and fake_3
. In some circumstances it'll de-duplicate the flag and apply it to only one of the libraries. Attempts to fix this like
target_link_libraries(lib_a PUBLIC "-Wl,-force_load $<TARGET_PROPERTY:fake_4,IMPORTED_LOCATION>")
cause the linker flags to be placed before the library, but then cmake doesn't recognize the imported libs for what they are so it ignores the dependencies between them.
A full example project that exhibits these issues can be found here: https://github.com/REVLUTION/cmake-example
There's more details there and you can also see suggestions that didn't work on a StackOverflow post (https://stackoverflow.com/questions/59204159/force-linked-static-libraries-with-cmake-not-working) and the cmake discussion forums (https://discourse.cmake.org/t/wl-force-link-flags-not-working-correctly/322/7). Given that nobody seems to have a way to do this correctly I'm starting to suspect that it's just not possible and is a bug.