How to conditionally add ALL option to add_custom_target()?

本秂侑毒 提交于 2021-01-29 04:20:55

问题


I would like to conditionally include the target docs_html to ALL if user selects ${DO_HTML} switch in cmake-gui. How to do without this ugly code repetition?

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:


You may use variable's dereference to form conditional parts of command's invocation. Empty values (e.g. if variable is absent) is simply ignored:

# 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
)

Variable may contain even several parameters to the command. E.g. one may conditionally add additional COMMAND clause for the target:

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
)


来源:https://stackoverflow.com/questions/41572275/how-to-conditionally-add-all-option-to-add-custom-target

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!