如何有条件地将 ALL 选项添加到 add_custom_target()?

2024-06-19

我想有条件地包含目标docs_html to ALL如果用户选择 ${DO_HTML} 切换cmake-gui。如何避免这种丑陋的代码重复?

cmake_minimum_required(VERSION 3.3 FATAL_ERROR)
project(docs)

set(DO_HTML 1 CACHE BOOL "Whether generate documentation in static HTML")

if (${DO_HTML})
#This command doesn't work:
#       add_dependencies(ALL docs_html)

    add_custom_target(docs_html ALL   #Code repeat 1
        DEPENDS ${HTML_DIR}/index.html
    )
else()
    add_custom_target(docs_html       #Code repeat 2
        DEPENDS ${HTML_DIR}/index.html
    )
endif()

您可以使用变量的取消引用来形成有条件的部分命令的调用。空值(例如,如果变量不存在)将被简单地忽略:

# Conditionally form variable's content.
if (DO_HTML)
    set(ALL_OPTION ALL)
# If you prefer to not use uninitialized variables, uncomment next 2 lines.
# else()
# set(ALL_OPTION)
endif()

# Use variable in command's invocation.
add_custom_target(docs_html ${ALL_OPTION}
        DEPENDS ${HTML_DIR}/index.html
)

变量甚至可以包含几个参数到命令。例如。可以有条件地添加额外的COMMAND目标条款:

if(NEED_ADDITIONAL_ACTION) # Some condition
    set(ADDITIONAL_ACTION COMMAND ./run_something arg1)
endif()

add_custom_target(docs_html ${ALL_OPTION}
    ${ADDITIONAL_ACTION}
    DEPENDS ${HTML_DIR}/index.html
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何有条件地将 ALL 选项添加到 add_custom_target()? 的相关文章

随机推荐