2017-01-10 54 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 
) 
相關問題