Skip to content
systemcoding.dev
Toolchains

Set the C standard with CMAKE_C_STANDARD and CMAKE_C_STANDARD_REQUIRED

Pin the C language level in CMake 3.31 with CMAKE_C_STANDARD, and make it an error rather than a silent downgrade with CMAKE_C_STANDARD_REQUIRED.

1 min read
Summarize in AI

You want every target in a project built as C11, not whatever the compiler defaults to. Two cache-style variables do it in CMake 3.31, and the second one is the one people forget: without CMAKE_C_STANDARD_REQUIRED, CMake treats the standard as a request and quietly falls back to an older one if the compiler lacks it.

CMakeLists.txtcmake
cmake_minimum_required(VERSION 3.20)
project(demo C)

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)

add_executable(demo main.c)
Text
/usr/bin/cc -std=c11 -MD -MT CMakeFiles/demo.dir/main.c.o -MF CMakeFiles/demo.dir/main.c.o.d -o CMakeFiles/demo.dir/main.c.o -c /src/demo/main.c

With extensions on, which is the default, GCC 14 would get -std=gnu11 and accept GNU-only syntax without a word. Turning CMAKE_C_EXTENSIONS off gives the strict -std=c11 shown above. These variables only seed the properties of targets created after the set() line, so put them before add_executable. The CMAKE_C_STANDARD page lists the accepted values.

For a library that others consume, do not force a standard on them from the top level; use target_compile_features on the target instead.

Taggedccmake
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.