仅当依赖项满足时才创建 CMake 目标

Create CMake target only if dependencies satisified

我有一个包含多个库和可执行文件的 CMake 项目。某些目标具有可能无法在所有平台上得到满足的依赖项。在这种情况下,我希望 CMake 能够工作并生成有意义的 Makefile(或其他构建项目)。

例如:

在安装了 libX11 的系统上,可以构建所有目标。在没有的系统上,只能构建 execQUUX

目前我正在做这样的事情:

# work out if we can build this target
set(buildLibFOO LibX11_FOUND)

if (${buildLibFOO})
    add_library(libFOO ... )
    target_link_libraries(libFOO LibX11_LIBRARY)
endif()

set(buildExecBAR true)

# work out if we can build this target
if (NOT TARGET libFOO)
    set(buildExecBAR false)
endif()

if (${buildExecBAR})
    add_exec(execBAR ...)
    target_link_libraries(execBAR libFOO)
endif() 

# always build this one
add_exec(execQUUX ...)

然而,这感觉有点笨拙,因为我需要仔细考虑为每个目标检查什么,而不是告诉 CMake "these deps are required for these targets, if missing, omit the target"。

有没有更简单(或更正确)的方法来做到这一点?

these deps are required for these targets, if missing, omit the target

据我所知,CMake中没有这样的功能。

但是您可以创建函数,它仅在满足其依赖项时才添加 library/executable。像这样:

include(CMakeParseArguments)

# Similar as *add_executable*, but additionally accepts DEPENDS option.
# All arguments after this option are treated as libraries targets for link with;
# executable is created only when these targets exist.
function(add_executable_depends name)
    cmake_parse_arguments(MY_EXEC "" "" "DEPENDS" ${ARGN})
    foreach(depend ${MY_EXEC_DEPENDS})
        if(NOT TARGET ${depend})
            return()
        endif()
    endforeach()
    add_executable(${name} ${MY_EXEC_UNPARSED_ARGUMENTS})
    target_link_libraries(${name} ${MY_EXEC_DEPENDS})
endfunction()

用法示例:

# work out if we can build this target
set(buildLibFOO LibX11_FOUND)

if (${buildLibFOO})
    add_library(libFOO ... )
    target_link_libraries(libFOO LibX11_LIBRARY)
endif()

# Add executable (and link with libFOO) only when libFOO exists.
add_executable_depends(execBAR ... DEPENDS libFOO)

# always build this one(similar to add_executable)
add_executable_depends(execQUUX ...)