5

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?

4

1 回答 1

14

CMake 命令target_link_libraries允许在链接给定目标时指定库和标志。MY_LIB不要在调用中直接使用目标名称,而是使用一个变量,该变量使用and标志TARGET_LINK_LIBRARIES包装对的引用:MY_LIB--whole-archive--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})
于 2013-07-04T20:12:47.873 回答