如何在cmake中将同一组库链接到多个目标/可执行文件?

nwo49xxi  于 2023-01-17  发布在  其他
关注(0)|答案(2)|浏览(215)

在我的项目结构中有多个可执行文件/目标文件,它们都使用相同的库。有没有办法使它更紧凑?也许是像for循环这样的东西?

set(ALL_LIBS lib1 lib2 lib3) # etc.

add_executable(program1 program1.cpp)
target_link_libraries(program1 PRIVATE ${ALL_LIBS})

add_executable(program2 program2.cpp)
target_link_libraries(program2 PRIVATE ${ALL_LIBS})

add_executable(program3 program3.cpp)
target_link_libraries(program3 PRIVATE ${ALL_LIBS})

add_executable(program4 program4.cpp)
target_link_libraries(program4 PRIVATE ${ALL_LIBS})

我正在寻找一个解决方案,实现类似的东西或比这更干净:

add_executable(program1 program1.cpp)
add_executable(program2 program2.cpp)
add_executable(program3 program3.cpp)
add_executable(program4 program4.cpp)

# somehow get list of target names
foreach(${TARGETS})
    # link libraries to each target
    target_link_libraries(${TARGET_NAME} PRIVATE ${ALL_LIBS})
endforeach()
s4n0splo

s4n0splo1#

您可以定义自己的宏或函数,它定义了一个类似于普通add_executable的可执行文件,但也将该可执行文件与公共库链接。

set(ALL_LIBS lib1 lib2 lib3) # etc.

# A wrapper around add_executable which links all created executables with libraries
function(add_executable_common name)
  # Forward all parameters to add_executable
  add_executable(${ARGV})
  # Perform additional actions
  target_link_libraries(${name} PRIVATE ${ALL_LIBS})
endfunction()

# Created function can be used in the very same manner as add_executable.

add_executable_common(program1 program1.cpp)
add_executable_common(program2 program2.cpp)
add_executable_common(program3 program3.cpp)
add_executable_common(program4 program4.cpp)

CMake变量ARGVARGN提供了一个完美的方法来将一个函数/宏的参数转发到另一个函数/宏。这允许轻松地创建现有函数的 Package 器,而不需要解析 Package 函数所需的所有参数。
例如,虽然上面定义的函数add_executable_common不解析除第一个参数之外的参数,但是它仍然可以用于定义STATIC或SHARED库,并且可以用于定义具有多个源的库:

add_executable_common(program5 SHARED program5.cpp additional_algos.cpp)
v440hwme

v440hwme2#

我找到了一个不错的解决方案来减少行数。我只是创建了一个函数来接受目标名称和文件路径。

function(add_program_target TARGET_NAME)
    add_executable(${TARGET_NAME} ${ARGN})
    target_link_libraries(${TARGET_NAME} PRIVATE ${ALL_LIBS})
endfunction()

然后我就像这样添加目标:

add_program_target(program1 program1.cpp helper.cpp)
add_program_target(program2 program2.cpp)
add_program_target(program2 program3.cpp)
add_program_target(program2 program4.cpp)
# etc.

相关问题