Cmake generator for all executables

Viewed 32

I have several executables:

add_executable(exe1 ${DRIVERS_DIR}/exe1.cpp)
add_executable(exe2 ${DRIVERS_DIR}/exe2.cpp)
add_executable(exe3 ${DRIVERS_DIR}/exe3.cpp)

And I need to add a link library to all of them:

target_link_libraries(exe1 ${LIB_NAME})
target_link_libraries(exe2 ${LIB_NAME})
target_link_libraries(exe3 ${LIB_NAME})

How can I replace three target_link_libraries with a single one with generator expression for exe1, exe2, exe3 ?

2 Answers

with generator expression for exe1, exe2, exe3?

You cannot use a generator expression in the target argument of target_link_libraries, period. It simply is impossible.

How can I replace three target_link_libraries with a single one[?]

You can use a loop:

set(exes exe1 exe2 exe3)
foreach (exe IN LISTS exes)
  add_executable("${exe}" "${DRIVERS_DIR}/${exe}.cpp")
  target_link_libraries("${exe}" PRIVATE "${LIB_NAME}")
endforeach ()

This looks pretty clean to me.

You cannot use generator expressions here.

It's pretty simple to create a function for creating the executable and linking it though:

#[===[
 Usage:
        my_create_linked_exe(target source...)
]===]
function(my_create_linked_exe TARGET SRC)
    add_executable(${TARGET} ${SRC} ${ARGN})
    target_link_libraries(${TARGET} PRIVATE ${LIB_NAME})
endfunction()

my_create_linked_exe(exe1 ${DRIVERS_DIR}/exe1.cpp)
my_create_linked_exe(exe2 ${DRIVERS_DIR}/exe2.cpp)

# helper.cpp only added to demonstrate you could pass more than a single parameter
my_create_linked_exe(exe3 ${DRIVERS_DIR}/exe3.cpp ${DRIVERS_DIR}/helper.cpp)
Related