1

There are 4 libs linked already and want to link a new library if FLAG is ON.

target_link_libraries (lib1 lib2 lib3 lib4 ${CMAKE_DL_LIBS})

I want it to be something like

target_link_libraries (lib1 lib2 lib3 lib4 if(FLAG) lib5 endif() ${CMAKE_DL_LIBS})

Is there anyway to implement this in cmakelists.txt?

etch_45
  • 792
  • 1
  • 6
  • 21
Ashwini
  • 11
  • 2
  • You may **conditionally** (under `if` command) set a variable and (unconditionally) pass this variable to the `target_link_libraries` call. See e.g. that question: https://stackoverflow.com/q/41572275/3440745. Alternatively, you could **conditionally** call `target_link_libraries(lib1 lib5)`. – Tsyvarev Dec 09 '20 at 19:22

1 Answers1

2

Simply use multiple target_link_library commands.

E.g. the following could be used to add a lib for unix targets

target_link_libraries (lib1 lib2 lib3 lib4 ${CMAKE_DL_LIBS})

if(UNIX)
    target_link_libraries(lib1 lib5)
endif()

Alternatively you could use a list containing the libs to include

set(LIBS lib2 lib3 lib4 ${CMAKE_DL_LIBS})

if(UNIX)
    list(APPEND LIBS lib5)
endif()

target_link_libraries(lib1 ${LIBS})

In theory you could also use generator expressions, but imho this would make for the least readable alternative

target_link_libraries(lib1 lib2 lib3 lib4 ${CMAKE_DL_LIBS} $<$<BOOL:${UNIX}>:lib5>)
fabian
  • 80,457
  • 12
  • 86
  • 114