CMAKE_COMMAND script policy

CMAKE_COMMAND can be used to directly invoke CMake scripts with options. This is particularly useful to chain CMake scripts during tests with fixtures. It’s important to set the minimum CMake version in the top-level called script as otherwise CMake defaults to extremely old policies that may make current CMake syntax fail in puzzling ways. Just like CMakeLists.txt, setting a policy at the top level script propagates globally.

Example: suppose we have a test script that reads a file using regex. This will fail without cmake_minimum_required() or cmake_policy(). I prefer cmake_minimum_required to make the script fail if someone uses the script directly with too-old CMake.

add_test(NAME myRegex COMMAND ${CMAKE_COMMAND} ${CMAKE_CURRENT_SOURCE_DIR}/mytest.cmake)

mytest.cmake contains:

cmake_minimum_required(3.13...3.20)  # whatever sensible minimum

file(STRINGS my.txt m REGEX "([\.A-Za-z0-9_]+)")

The failure will be over escaped \. if cmake_minimum_version or cmake_policy isn’t used in mytest.cmake.