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

參見