Skip to content

Instantly share code, notes, and snippets.

@scivision
Last active January 31, 2024 16:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save scivision/8fe5812bcb56ac28e7a1e41f1f9a689d to your computer and use it in GitHub Desktop.
CMake force use of presets

CMake force use of presets

This approach uses a sentinel environment variable to effectively force the users to use CMake Presets for configure and build steps.

This approach uses a small auxiliary CMake script as a PRE_BUILD step for a target to check a sentinel environment variable and fail the configure or build step if it is not set.

Tested with CMake generators: MinGW Makefiles, Ninja, Unix Makefiles, Visual Studio 17 2022

Reference question

These non-preset command sequences all fail intentionally as they don't use presets:

cmake -Bbuild

# or

cmake --preset default
cmake --build build

These preset commands succeed

cmake --preset default

cmake --build --preset default
if(NOT DEFINED ENV{sentinel})
message(FATAL_ERROR "sentinel not set--cmake presets must be used")
endif()
# force use of presets via sentinel environment variable set in presets only
cmake_minimum_required(VERSION 3.21)
project(envpre LANGUAGES C)
message(STATUS "sentinel: $ENV{sentinel}")
include(CheckSentinel.cmake)
add_executable(main main.c)
add_custom_command(
TARGET main
PRE_BUILD
COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/CheckSentinel.cmake
)
{
"version": 3,
"configurePresets": [
{
"name": "default",
"displayName": "Default Config",
"binaryDir": "${sourceDir}/build",
"environment": {
"sentinel": "MyConfigure"
}
}
],
"buildPresets": [
{
"name": "default",
"configurePreset": "default",
"environment": {
"sentinel": "MyBuild"
}
}
]
}
int main() { return 0; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment