Reputation: 1184
I have a static link library (say libfoo).
add_library(foo STATIC foo.cpp)
There are many executables that links(uses) this library.
add_executable(myexe1 myexe1.cpp)
link_target_libraries(myexe1 foo)
add_executable(myexe2 myexe2.cpp)
link_target_libraries(myexe2 foo)
add_executable(myexe3 myexe3.cpp)
link_target_libraries(myexe3 foo)
#... and so on. (These definitions are actually scattered in the project)
Now I would like to use -Wl,--whole-archive
flag to the library.
It seems one solution is to add the flags in the executable side.
add_executable(myexe1 myexe1.cpp)
link_target_libraries(myexe1 -Wl,--whole-archive foo -Wl,--no-whole-archive)
But in this way I have to write this every time I define executable that links to this library.
Is there any way to add this flag to the library definition side so that the flag is always used when linking the executables that depend on the library?
Upvotes: 6
Views: 5513
Reputation: 652
I had the same problem, but could not stop CMAKE from reordering the flags and my library. I ended up doing something like this:
add_library(foo_actual STATIC foo.cpp)
add_library(foo INTERFACE)
set_property(TARGET foo PROPERTY INTERFACE_LINK_LIBRARIES
-Wl,--whole-archive,$<TARGET_FILE:foo_actual>,--no-whole-archive)
Couple differences with your answer:
$<TARGET_FILE>
worked well and ensures the dependency is propagated.--whole-archive
, library, and --no-whole-archive
all in one argument, so CMake wouldn't reorder them. I could not get CMake not to wildly reorder them, otherwise.Upvotes: 4
Reputation: 1184
I solved this with the following solution.
add_library(foo STATIC foo.cpp)
get_property(foo_location TARGET foo PROPERTY LOCATION)
target_link_libraries(foo -Wl,--whole-archive ${foo_location} -Wl,--no-whole-archive)
Upvotes: 2