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

另请参阅