return¶
從檔案、目錄或函式返回。
return([PROPAGATE <var-name>...])
當在包含的檔案(透過 include()
或 find_package()
)中遇到此命令時,它會導致停止處理當前檔案,並將控制權返回給包含該檔案的檔案。如果它在另一個檔案未包含的檔案中遇到,例如 CMakeLists.txt
,則會調用由 cmake_language(DEFER)
排定的延遲呼叫,並且如果有父目錄,則將控制權返回給父目錄。
如果在函式中呼叫 return()
,則控制權會返回給該函式的呼叫者。 請注意,macro()
與 function()
不同,它是就地展開的,因此無法處理 return()
。
政策 CMP0140
控制有關命令參數的行為。 除非該政策設定為 NEW
,否則所有參數都會被忽略。
PROPAGATE
在版本 3.25 中新增。
此選項會在父目錄或函式呼叫者範圍中設定或取消設定指定的變數。 這等同於
set(PARENT_SCOPE)
或unset(PARENT_SCOPE)
命令,除了它與block()
命令互動的方式,如下所述。PROPAGATE
選項與block()
命令結合使用時非常有用。return
將通過block()
命令建立的任何封閉區塊範圍傳播指定的變數。 在函式內部,這可確保變數傳播到函式的呼叫者,而與函式內的任何區塊無關。 如果不在函式內,則確保變數傳播到父檔案或目錄範圍。 例如CMakeLists.txt¶cmake_minimum_required(VERSION 3.25) project(example) set(var1 "top-value") block(SCOPE_FOR VARIABLES) add_subdirectory(subDir) # var1 has the value "block-nested" endblock() # var1 has the value "top-value"
subDir/CMakeLists.txt¶function(multi_scopes result_var1 result_var2) block(SCOPE_FOR VARIABLES) # This would only propagate out of the immediate block, not to # the caller of the function. #set(${result_var1} "new-value" PARENT_SCOPE) #unset(${result_var2} PARENT_SCOPE) # This propagates the variables through the enclosing block and # out to the caller of the function. set(${result_var1} "new-value") unset(${result_var2}) return(PROPAGATE ${result_var1} ${result_var2}) endblock() endfunction() set(var1 "some-value") set(var2 "another-value") multi_scopes(var1 var2) # Now var1 will hold "new-value" and var2 will be unset block(SCOPE_FOR VARIABLES) # This return() will set var1 in the directory scope that included us # via add_subdirectory(). The surrounding block() here does not limit # propagation to the current file, but the block() in the parent # directory scope does prevent propagation going any further. set(var1 "block-nested") return(PROPAGATE var1) endblock()