cmakegenerator-expression

Using CMake generator expressions to link if target exists


I have this CMakeLists.txt snippet:

if (TARGET bar)
  target_link_libraries(foo PUBLIC bar)
else()
  target_link_libraries(foo PUBLIC baz)
endif()

I imagine I can make this shorter with CMake's generator expressions. How would I do that?

I tried:

target_link_library(foo PUBLIC $<IF:$<TARGET_EXISTS:bar>,bar,baz> )

but in practice, foo doesn't appear link to either library.


Solution

  • Similar, but not identical logic that seems to work is:

    target_link_library(foo PUBLIC
      $<TARGET_NAME_IF_EXISTS:bar>
      $<TARGET_NAME_IF_EXISTS:baz>
    )