CMake中的while命令用于在条件为true时评估(evaluate)一组命令,其格式如下:
while(<condition>)
<commands>
endwhile()
在while和匹配的endwhile之间的所有命令都被记录下来而不被调用。一旦评估了endwhile,只要<condition>为true,就会调用记录的命令列表。
while中的<condition>与if命令中的<condition>具有相同语法和相同的逻辑进行评估。
命令break和continue提供了从正常控制流中退出的方法。
set(var 1)
while(${var} LESS 4)
message("var: ${var}")
math(EXPR var "${var}+1")
endwhile()
CMake中的continue命令用于continue到foreach或while循环的顶部(top),其格式如下:
continue()
continue命令允许cmake脚本中止foreach或while循环的当前迭代的其余部分,并从下一次迭代的顶部开始。
set(var 1)
while(${var} LESS 4)
message("var: ${var}")
math(EXPR var "${var}+1")
if(${var} EQUAL 3)
continue()
endif()
message("after math, var: ${var}")
endwhile()
CMake中的break命令用于从foreach或while循环中中断(break),其格式如下:从当前的foreach或while循环中退出
break()
set(var 1)
while(${var} LESS 4)
message("var: ${var}")
math(EXPR var "${var}+1")
if(${var} EQUAL 3)
break()
endif()
message("after math, var: ${var}")
endwhile()
message("var: ${var}")
执行上述测试代码需要3个文件:build.sh, CMakeLists.txt, test_while.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_while.cmake:为上面的所有示例代码
可能的执行结果如下图所示:
GitHub: https://github.com/fengbingchun/Linux_Code_Test