如何在 CMake 中设置 --whole-archive 标志,以便所有依赖项使用它

Shu*_*uki 5 c c++ cmake

我有一个静态链接库(比如 libfoo)。

 add_library(foo STATIC foo.cpp)
Run Code Online (Sandbox Code Playgroud)

有许多可执行文件链接(使用)这个库。

 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)
Run Code Online (Sandbox Code Playgroud)

现在我想-Wl,--whole-archive对图书馆使用标志。似乎一种解决方案是在可执行端添加标志。

 add_executable(myexe1 myexe1.cpp)
 link_target_libraries(myexe1 -Wl,--whole-archive foo -Wl,--no-whole-archive)
Run Code Online (Sandbox Code Playgroud)

但是这样我每次定义链接到这个库的可执行文件时都必须写这个。

有没有办法将此标志添加到库定义端,以便在链接依赖库的可执行文件时始终使用该标志?

Shu*_*uki 2

我用以下解决方案解决了这个问题。

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) 
Run Code Online (Sandbox Code Playgroud)