CMake中的option命令为用户提供可以选择的布尔选项(boolean option),其格式如下:
option( "" [value])
如果未提供初始
在CMake项目模式(project mode)下,使用选项值创建一个布尔缓存变量。在CMake脚本模式(script mode)下,使用选项值设置一个布尔变量。
- option(BUILD_CUDA "build cuda" ON)
- if(BUILD_CUDA)
- message("option BUILD_CUDA: ON") # print
- endif()
-
- option(BUILD_CAFFE "build caffe" OFF)
- if(BUILD_CAFFE)
- message("option BUILD_CAFFE: ON") # won't print
- endif()
- if(NOT BUILD_CAFFE)
- message("option BUILD_CAFFE: OFF") # print
- endif()
CMake option在命令行上的设置:形式如: cmake -DBUILD_PYTORCH=ON ..
- if(BUILD_PYTORCH)
- message("option BUILD_PYTORCH: ON") # print
- endif()
CMake中的cmake_dependent_option是一个宏,提供依赖于其它选项的选项的宏(macro to provide an option dependent on other options)。仅当一组其它条件为true时,此宏才会向用户提供一个选项。其格式如下:
cmake_dependent_option(
(1).如果
- option(USE_BAR "USE BAR" ON)
- option(USE_ZOT "use zot" OFF)
-
- include(CMakeDependentOption) # module CMakeDependentOption provides the cmake_dependent_option macro
- cmake_dependent_option(USE_FOO "Use Foo" ON "USE_BAR;NOT USE_ZOT" OFF)
-
- if(USE_FOO)
- message("cmake_dependent_option USE_FOO: ON") # print
- endif()
option和cmake_dependent_option中变量的值会存储在CMakeCache.txt中。因此若调整其中变量的值需删除CMakeCache.txt后才会生效。
执行上述测试代码需要3个文件:build.sh, CMakeLists.txt, test_option.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)
-
- 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_option.cmake:为上面的所有示例代码
可能的执行结果如下图所示:
