Skip to content
systemcoding.dev
Toolchains

Require a language level per target with target_compile_features

Use target_compile_features(app PRIVATE cxx_std_20) in CMake 3.31 so each target states the C++ level it needs and consumers inherit it.

1 min read
Summarize in AI

A global CMAKE_CXX_STANDARD says nothing about which target actually needs C++20. target_compile_features attaches the requirement to the target, and with PUBLIC or INTERFACE it travels to everything that links the library. This is the form to use in CMake 3.31 for anything you plan to share.

CMakeLists.txtcmake
cmake_minimum_required(VERSION 3.20)
project(span_demo CXX)

add_library(buf STATIC buf.cpp)
target_compile_features(buf PUBLIC cxx_std_20)

add_executable(app main.cpp)
target_link_libraries(app PRIVATE buf)
Text
/usr/bin/c++ -std=gnu++20 -o CMakeFiles/app.dir/main.cpp.o -c /src/span_demo/main.cpp

app never asked for C++20, yet it was compiled with -std=gnu++20 because buf declared it PUBLIC. Making it PRIVATE would keep the requirement on buf alone. The flag spelling is picked per compiler, so you never write -std= yourself. The documented behaviour is in target_compile_features.

If the project also sets CMAKE_CXX_STANDARD to something higher, the higher one wins. And cxx_std_20 only asks for a minimum: a compiler that defaults to C++23 keeps its own default.

Taggedcppcmake
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.