如何有条件地添加“ALL”选项到add_custom_target()函数中?

3
我希望在用户在cmake-gui中选择了${DO_HTML}开关后,有条件地将目标docs_html包含到ALL中。如何做到不重复编写这个丑陋的代码?
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()
1个回答

3
您可以使用变量解引用来组成命令调用的条件部分。空值(例如,如果变量不存在)将被简单地忽略:
# 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
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接