CMake中的return命令用于从文件、目录或函数返回,其格式如下:
return([PROPAGATE <var-name>...])
当在包含文件中(in an included file)遇到此命令时(通过include或find_package命令),它会导致当前文件的处理停止并将控制权返回给包含文件(including file)。如果在另一个文件不包含的文件中遇到它,例如CMakeLists.txt,调用由cmake_language(DEFER)安排的延迟调用,如果有的话,则控制权返回到父目录。
如果在function中调用return,则将控制权返回给function的调用者。注意:与function不同,macro是在原地(in place)展开的,因此无法处理return.
Policy CMP0140控制return命令参数的行为。除非该策略设置为NEW,否则所有参数都将被忽略。
PROPAGATE:3.25版本中引入。此选项用于父目录或function调用者范围中set或unset指定的变量。这相当于set(PARENT_SCOPE)或unset(PARENT_SCOPE)命令。
function(func1 addr)
set(${addr} "https://blog.csdn.net/fengbingchun" PARENT_SCOPE)
endfunction()
function(func2 addr)
return()
set(${addr} "https://blog.csdn.net/fengbingchun" PARENT_SCOPE)
endfunction()
set(addr "csdn:")
func1(addr)
message("addr: ${addr}") # addr: https://blog.csdn.net/fengbingchun
set(addr "csdn:")
func2(addr)
message("addr: ${addr}") # addr: csdn:
执行上述测试代码需要3个文件:build.sh, CMakeLists.txt, test_return.cmake
build.sh内容如下:
#! /bin/bash
# supported input parameters(cmake commands)
params=(function macro cmake_parse_arguments \
find_library find_path find_file find_program find_package \
cmake_policy cmake_minimum_required project include \
string list set foreach message option if while return \
math file)
usage()
{
echo "Error: $0 needs to have an input parameter"
echo "supported input parameters:"
for param in ${params[@]}; do
echo " $0 ${param}"
done
exit -1
}
if [ $# != 1 ]; then
usage
fi
flag=0
for param in ${params[@]}; do
if [ $1 == ${param} ]; then
flag=1
break
fi
done
if [ ${flag} == 0 ]; then
echo "Error: parameter \"$1\" is not supported"
usage
exit -1
fi
if [[ ! -d "build" ]]; then
mkdir build
cd build
else
cd build
fi
echo "==== test $1 ===="
# test_set.cmake: cmake -DTEST_CMAKE_FEATURE=$1 --log-level=verbose ..
# test_option.cmake: cmake -DTEST_CMAKE_FEATURE=$1 -DBUILD_PYTORCH=ON ..
cmake -DTEST_CMAKE_FEATURE=$1 ..
# It can be executed directly on the terminal, no need to execute build.sh, for example: cmake -P test_set.cmake
CMakeLists.txt内容如下:
cmake_minimum_required(VERSION 3.22)
project(cmake_feature_usage)
message("#### current cmake version: ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}.${CMAKE_PATCH_VERSION}")
include(test_${TEST_CMAKE_FEATURE}.cmake)
message("==== test finish ====")
test_return.cmake:为上面的所有示例代码
可能的执行结果如下图所示:
GitHub: https://github.com/fengbingchun/Linux_Code_Test