Search code examples
c++cmakec++20fmtstdformat

How to use C++20 <format> in CMake project


I want to use the <format> header available in C++20.

I am using the most up-to-date release of CMake.

My CMakeFiles looks like

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_BUILD_TYPE debug)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++20")

I am using Clang 9 as my compiler.

However, I am getting the following error when including <format>:

fatal error: 'format' file not found
#include <format>

I have also used the flag -std=c++2a, with no effect. How can I use C++20 <format>?


Solution

  • According to the C++ compiler support page (archive) on cppreference, C++20 <format> functionalities are fully supported by

    • GCC libstdc++ 13;

    • MSVC STL 19.29 (Visual Studio 2019 16.10); and

    • Clang libc++ 17.*

    You will be able to use #include <format> normally after upgrading to these versions.

    If upgrading is not an option for one reason or another, you can still use the {fmt} library, which was the basis for the standardization of the C++20 <format> library. There are minimal differences between C++20 <format> and the {fmt} library.


    * Experimental support is available since Clang libc++ 14 through the -fexperimental-library compiler flag.