CMakePushCheckState¶
该模块提供了用于管理变量状态的宏,这些变量影响各种 CMake 检查命令(例如,check_symbol_exists()
等)的执行方式。这些宏保存、重置和恢复以下变量
CMAKE_REQUIRED_FLAGS
CMAKE_REQUIRED_DEFINITIONS
CMAKE_REQUIRED_INCLUDES
CMAKE_REQUIRED_LINK_OPTIONS
CMAKE_REQUIRED_LIBRARIES
CMAKE_REQUIRED_LINK_DIRECTORIES
CMAKE_REQUIRED_QUIET
CMAKE_EXTRA_INCLUDE_FILES
宏¶
- cmake_push_check_state¶
将上述变量的当前状态保存(推入)到堆栈中。这通常用于在为特定检查进行临时修改之前保留当前配置。
cmake_push_check_state([RESET])
RESET
当指定此选项时,该宏不仅保存列出的变量的当前状态,还会将它们重置为空,从而允许从干净的状态重新配置它们。
- cmake_reset_check_state¶
将上面列出的变量的内容重置(清除)为空状态。
cmake_reset_check_state()
例如,当执行需要全新配置的多个顺序检查时,可以使用此宏,以确保先前的配置不会无意中延续下去。
- cmake_pop_check_state¶
将上面列出的变量的状态恢复到最近一次
cmake_push_check_state()
调用时的值。cmake_pop_check_state()
此宏用于恢复在检查期间所做的临时更改。为防止意外行为,请将每个
cmake_push_check_state()
与相应的cmake_pop_check_state()
配对使用。
这些宏对于作用域配置非常有用,例如,在查找模块中或在受控环境中执行检查时,确保临时修改隔离在检查的范围内,并且不会传播到构建系统的其他部分。
注意
其他 CMake 变量,例如 CMAKE_<LANG>_FLAGS
,会传播到所有检查,而与这些宏无关,因为这些基本变量旨在影响构建系统的全局状态。
示例¶
include(CMakePushCheckState)
# Save and reset the current state
cmake_push_check_state(RESET)
# Perform check with specific compile definitions
set(CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
include(CheckSymbolExists)
check_symbol_exists(memfd_create "sys/mman.h" HAVE_MEMFD_CREATE)
# Restore the original state
cmake_pop_check_state()
变量状态可以多次推入堆栈,从而允许嵌套或顺序配置。每个 cmake_pop_check_state()
都会恢复最近推送的状态。
include(CMakePushCheckState)
# Save and reset the current state
cmake_push_check_state(RESET)
# Perform the first check with additional libraries
set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_DL_LIBS})
include(CheckSymbolExists)
check_symbol_exists(dlopen "dlfcn.h" HAVE_DLOPEN)
# Save current state
cmake_push_check_state()
# Perform the second check with libraries and additional compile definitions
set(CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
check_symbol_exists(dladdr "dlfcn.h" HAVE_DLADDR)
message(STATUS "${CMAKE_REQUIRED_DEFINITIONS}")
# Output: -D_GNU_SOURCE
# Restore the previous state
cmake_pop_check_state()
message(STATUS "${CMAKE_REQUIRED_DEFINITIONS}")
# Output here is empty
# Reset variables to prepare for the next check
cmake_reset_check_state()
# Perform the next check only with additional compile definitions
set(CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
check_symbol_exists(dl_iterate_phdr "link.h" HAVE_DL_ITERATE_PHDR)
# Restore the original state
cmake_pop_check_state()