Errors when using WHOLE_ARCHIVE link feature with circular static libraries
I'm trying to use WHOLE_ARCHIVE Link Feature to force include all symbols of static libraries into a shared library.
The static libraries I'm trying to include has circular dependency, example (A library depends on B library, and B library depends on A library).
Minimum CMakeLists.txt example:
cmake_minimum_required(VERSION 3.25)
project(test)
add_library(A STATIC a.c)
add_library(B STATIC b.c)
target_link_libraries(A PRIVATE B)
target_link_libraries(B PRIVATE A)
add_library(top_whole_archive SHARED top.c)
target_link_libraries(top_whole_archive PRIVATE $<LINK_LIBRARY:WHOLE_ARCHIVE,A>)
However, these errors are produced at CMake configure:
-- Configuring done
CMake Error at CMakeLists.txt:10 (add_library):
Impossible to link target 'top_whole_archive' because the link item 'A',
specified without any feature or 'DEFAULT' feature, has already occurred
with the feature 'WHOLE_ARCHIVE', which is not allowed.
-- Generating done
CMake Generate step failed. Build files cannot be regenerated correctly.
I tried to workaround this using LINK_LIBRARY_OVERRIDE property like this:
set_property(TARGET top_whole_archive PROPERTY LINK_LIBRARY_OVERRIDE "WHOLE_ARCHIVE,A")
But this also produced link errors at CMake build:
[6/6] Linking C shared library libtop_whole_archive.so
FAILED: libtop_whole_archive.so
: && cc -fPIC -shared -Wl,-soname,libtop_whole_archive.so -o libtop_whole_archive.so CMakeFiles/top_whole_archive.dir/top.c.o -Wl,--push-state,--whole-archive libA.a -Wl,--pop-state libB.a -Wl,--push-state,--whole-archive libA.a -Wl,--pop-state libB.a && :
libA.a(a.c.o): In function `a_func':
a.c:(.text+0x0): multiple definition of `a_func'
libA.a(a.c.o):a.c:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
We notice the link command duplicated libA.a whole archive, probably due to the circular dependency, I think this should not be necessary since we already decided to include all symbols of A.
Also, I was expecting the configure step to succeed without the need to specify LINK_LIBRARY_OVERRIDE.