C / cmake - how to add a linker flag to a (unused) library when the library is specified in TARGET_LINK_LIBRARIES?

In the root directory of my project, I have a subdirectory for my_lib and another for my_app . The my_lib library defines tables that populate the section defined by the linker, these tables are not used directly by my_app , therefore this library is not related.

To bind my_lib, I added a flag - whole-archive, as described here.

And it works!

In 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 CMakelist.txt of my_lib , I have:

 ADD_LIBRARY(MY_LIB my_lib.c ) TARGET_LINK_LIBRARIES(MY_LIB) 

In CMakelist.txt of my_app , I have:

 ADD_EXECUTABLE(my_app my_app.c) TARGET_LINK_LIBRARIES(my_app MY_LIB) 

My problem is that I just want to use this flag ( --whole-archive ) if my_lib is specified in TARGET_LINK_LIBRARIES in CMakelist.txt my_app .

If the last line is TARGET_LINK_LIBRARIES(my_app MY_LIB) , I don’t want to add "-Wl,--whole-archive -lMY_LIB -Wl,--no-whole-archive" to CMAKE_EXE_LINKER_FLAGS .

I tried to remove this flag from CMakelist.txt in the root directory and add the following to the CMakelist.txt in my_lib :

 SET_TARGET_PROPERTIES(MY_LIB PROPERTIES CMAKE_EXE_LINKER_FLAGS "-Wl,--whole-archive -lMY_LIB -Wl,--no-whole-archive") 

But that will not work.

How can i do this?

+5
source share
1 answer

The CMake target_link_libraries command allows you to specify both libraries and flags when linking this target. Instead of directly using the target name MY_LIB in the MY_LIB call TARGET_LINK_LIBRARIES use a variable that MY_LIB reference to MY_LIB with --whole-archive and --no-whole-archive :

 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}) 
+13
source

Source: https://habr.com/ru/post/1489707/


All Articles