How to specify interface link libraries of imported targets

Hi,

I’m trying to build a library with cyclic dependencies.

The whole thing involves four entities:

  • two imported static libraries (libA and libB)
    both are defined in
    a “…-config.cmake” file, that is imported via find_package
  • one static library (libC) that I define locally with add_library(libC STATIC ...)
  • one executable that depends on libC via target_link_libraries(EXE PRIVATE libC)
# this is done in the external library's ...-config.cmake-file
add_library(libA STATIC IMPORTED)
add_library(libB STATIC IMPORTED)

# my local code
add_library(libC STATIC libC.cpp)
target_link_libraries(libC PRIVATE libA)

add_executable(EXE main.cpp)
target_link_libraries(EXE PRIVATE libC)

The dependencies are as follows:

  • libC depends on libA as indicated above by the target_link_libraries-command
  • libA depends on libB
    this is already accounted for in the external module by
set_target_properties(libA PROPERTIES
  INTERFACE_LINK_LIBRARIES "\$<LINK_ONLY:libB>"
)
  • what makes things a bit tricky is, that libB depends both on libA and on libC

I managed to get this to work by manipulating the INTERFACE_LINK_LIBRARIES property of this imported target (following the discussion here: https://gitlab.kitware.com/cmake/cmake/-/issues/17964):

get_target_property(LIBS libB INTERFACE_LINK_LIBRARIES)
list(APPEND LIBS libA libC)
set_target_properties(libB PROPERTIES INTERFACE_LINK_LIBRARIES "${LIBS}")

I find this solution a bit verbose and expected to be able to use target_link_libraries to achieve the same, however using

target_link_libraries(libB INTERFACE libA libC)

fails with error

CMake Error at src/CMakeLists.txt:33 (target_link_libraries):
Cannot specify link libraries for target "libB" which is not
built by this project.

I was expecting that this works, because the documentation seems to allow this command for imported targets (https://cmake.org/cmake/help/latest/command/target_link_libraries.html): ...or as an IMPORTED library....

I also tried cmake_policy(SET CMP0079 NEW), but this didn’t change anything (my minimally required cmake version is 3.21).

In short my questions are:
Can I somehow make target_link_libraries work or is there another way to specify the dependencies that is more elegant than manipulating the properties?

Thanks in advance and best regards
oz

In the mean time I at least figured out how to tweak the property more compactly:

set_property(TARGET libB APPEND PROPERTY INTERFACE_LINK_LIBRARIES libA libC)

This is very nice - still, I would like to understand why target_link_libraries doesn’t work.