Set C/C++ standard
Filename: CMakeLists.txt
cmake_minimum_required(VERSION 3.31)
project(set-c-cxx-standard LANGUAGES C CXX)
add_executable(hello-c23 ./src/bin/hello-c23.c)
target_compile_features(hello-c23 PRIVATE c_std_23)
add_executable(hello-cxx23 ./src/bin/hello-cxx23.cpp)
target_compile_features(hello-cxx23 PRIVATE cxx_std_23)
Filename: src/bin/hello-c23.c
#include <stdio.h>
int main() {
printf("__STDC_VERSION__=%ld\n", __STDC_VERSION__);
return 0;
}
Filename: src/bin/hello-cxx23.cpp
#include <iostream>
int main() {
std::cout << "__cplusplus=" << __cplusplus << "\n";
return 0;
}
$ CC=clang-18 CXX=clang++-18 cmake -B ./build/
-- The C compiler identification is Clang 18.1.8
-- The CXX compiler identification is Clang 18.1.8
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/clang-18 - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/clang++-18 - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.8s)
-- Generating done (0.0s)
-- Build files have been written to: /workspaces/cmakebyexample.jcbhmr.com/listings/05-set-c-cxx-standard/build
$ cmake --build ./build/
[ 25%] Building C object CMakeFiles/hello-c23.dir/src/bin/hello-c23.c.o
[ 50%] Linking C executable hello-c23
[ 50%] Built target hello-c23
[ 75%] Building CXX object CMakeFiles/hello-cxx23.dir/src/bin/hello-cxx23.cpp.o
[100%] Linking CXX executable hello-cxx23
[100%] Built target hello-cxx23
$ ./build/hello-c23
__STDC_VERSION__=202311
$ ./build/hello-cxx23
__cplusplus=202302
When you run this example yourself make sure you have a compiler that supports C23 and C++23. You can set the C and C++ compiler that CMake will use by setting the CC
and CXX
environment variables.