In the root directory of my project, I have a subdirectory for my_lib
and another for my_app
.
The library my_lib
defines tables that populates a section defined by the linker, these tables are not used directly by my_app
, so this library is not linked.
To force my_lib to be linked I added the flag --whole-archive as described here.
And it works!
In the CMakelist.txt of the root directory I have the following:
SET(CMAKE_EXE_LINKER_FLAGS "-mmcu=cc430f6137 -Wl,--gc-sections -Wl,--whole-archive -lMY_LIB -Wl,--no-whole-archive")
ADD_SUBDIRECTORY(my_lib)
In the CMakelist.txt
of my_lib
I have:
ADD_LIBRARY(MY_LIB
my_lib.c
)
TARGET_LINK_LIBRARIES(MY_LIB)
In the CMakelist.txt
of my_app
I have:
ADD_EXECUTABLE(my_app my_app.c)
TARGET_LINK_LIBRARIES(my_app MY_LIB)
My problem is I just want to use this flag (--whole-archive
) if MY_LIB
is specified in the TARGET_LINK_LIBRARIES
in CMakelist.txt
of my_app
.
If the the last line TARGET_LINK_LIBRARIES(my_app MY_LIB)
is not there, I don't want to add "-Wl,--whole-archive -lMY_LIB -Wl,--no-whole-archive"
in the CMAKE_EXE_LINKER_FLAGS
.
I tried to remove this flag from the CMakelist.txt in root and add the following into the CMakelist.txt
in my_lib
subdirectory:
SET_TARGET_PROPERTIES(MY_LIB PROPERTIES CMAKE_EXE_LINKER_FLAGS "-Wl,--whole-archive -lMY_LIB -Wl,--no-whole-archive")
But this does not work.
How can I do this?
The CMake command target_link_libraries allows for specifying both libraries and flags when linking a given target. Instead of directly using the target name
MY_LIB
in theTARGET_LINK_LIBRARIES
call, use a variable that wraps the reference toMY_LIB
with the--whole-archive
and--no-whole-archive
flags: