C/cmake - how to add a linker flag to an (unused) library when the library is specified in TARGET_LINK_LIBRARIES?
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 the TARGET_LINK_LIBRARIES
call, use a variable that wraps the reference to MY_LIB
with the --whole-archive
and --no-whole-archive
flags:
ADD_LIBRARY(MY_LIB
my_lib.c
)
SET(MY_LIB_LINK_LIBRARIES -Wl,--whole-archive MY_LIB -Wl,--no-whole-archive)
...
ADD_EXECUTABLE(my_app my_app.c)
TARGET_LINK_LIBRARIES(my_app ${MY_LIB_LINK_LIBRARIES})
Related videos on Youtube
Lilás
Updated on September 20, 2022Comments
-
Lilás over 1 year
In the root directory of my project, I have a subdirectory for
my_lib
and another formy_app
. The librarymy_lib
defines tables that populates a section defined by the linker, these tables are not used directly bymy_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
ofmy_lib
I have:ADD_LIBRARY(MY_LIB my_lib.c ) TARGET_LINK_LIBRARIES(MY_LIB)
In the
CMakelist.txt
ofmy_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
) ifMY_LIB
is specified in theTARGET_LINK_LIBRARIES
inCMakelist.txt
ofmy_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 theCMAKE_EXE_LINKER_FLAGS
.I tried to remove this flag from the CMakelist.txt in root and add the following into the
CMakelist.txt
inmy_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?