CMake: target_link_libraries based on flag

2.5k Views Asked by At

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?

1

There are 1 best solutions below

0
On

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>)