CMake中的math用于评估数学表达式,其格式如下:
math(EXPR <variable> "<expression>" [OUTPUT_FORMAT <format>])
计算数学<expression>并将<variable>设置为结果值。expression的结果必须可以表示为64位有符号整数。
数学表达式必须以字符串形式给出(即用双引号括起来)。例如"5 * (10 + 13)",支持的运算符有+, -, *, /, %, |, &, ^, ~, <<, >>,和(...),它们与C代码中的含义相同。
十六进制数字在以0x为前缀时被识别,就像C代码一样。
根据选项OUTPUT_FORMAT对结果进行格式化,其中<format>是以下内容之一:
(1).HEXADECIMAL:C代码中的十六进制表示法,以"0x"开头。
(2).DECIMAL:十进制表示法。如果未指定OUTPUT_FORMAT选项,也将使用该选项。
math(EXPR var1 "10 + 10" OUTPUT_FORMAT DECIMAL)
message("var1: ${var1}") # var1: 20
math(EXPR var2 "10 + 10") # 默认使用DECIMAL
message("var2: ${var2}") # var2: 20
math(EXPR var3 "10 + 10" OUTPUT_FORMAT HEXADECIMAL)
message("var3: ${var3}") # var3: 0x14
math(EXPR var "10 - 5")
message("var: ${var}") # var: 5
math(EXPR var "10 * 5")
message("var: ${var}") # var: 50
math(EXPR var "10 / 5")
message("var: ${var}") # var: 2
math(EXPR var "10 % 5")
message("var: ${var}") # var: 0
math(EXPR var "10 | 5")
message("var: ${var}") # var: 15
math(EXPR var "10 & 5")
message("var: ${var}") # var: 0
执行上述测试代码需要3个文件:build.sh, CMakeLists.txt, test_math.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_math.cmake:为上面的所有示例代码
可能的执行结果如下图所示:
GitHub: https://github.com/fengbingchun/Linux_Code_Test