2017-01-10 56 views
0

如果用户在cmake-gui中选择$ {DO_HTML}开关,我希望有条件地包含目标docs_htmlALL。没有这个丑陋的代码重复如何做?如何有条件地将所有选项添加到add_custom_target()?

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

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

# 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 
) 
相关问题