Treat warnings as errors in CMake with CMAKE_COMPILE_WARNING_AS_ERROR
Turn warnings into errors for every target in CMake 3.24 and newer with CMAKE_COMPILE_WARNING_AS_ERROR, and switch it off again from the command line.
Most projects add -Werror by hand, and then a new compiler release breaks every downstream packager's build. CMake 3.24 added a switch that applies the right flag per compiler, and the part the manual mentions only briefly is that you can override it from the command line without editing any file.
cmake_minimum_required(VERSION 3.24)
project(demo C)
add_compile_options(-Wall -Wextra)
set(CMAKE_COMPILE_WARNING_AS_ERROR ON)
add_executable(demo main.c)cmake -S . -B build
cmake -S . -B build -DCMAKE_COMPILE_WARNING_AS_ERROR=OFFWith GCC 14 the variable adds -Werror to each compile line, and with MSVC it adds /WX, so the one setting works across toolchains. It also initialises the COMPILE_WARNING_AS_ERROR property on each target created afterwards, which is why set() goes above add_executable.
The second command is the escape hatch for a distribution packager who has a newer compiler that warns about code you have not touched yet. Keep it on in your own CI, where a new warning should fail the build, and leave it off for releases that other people compile. See the variable's page.