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

1

39

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>?

Lichee answered 22/2, 2020 at 0:55 Comment(1)
Good news! MSVC now supports text formatting.Fitzger
C
28

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.

Cordoba answered 22/2, 2020 at 4:51 Comment(4)
I wonder why this is the case. Is it that hard to implement <format>? More complex parts like "concepts" seem to be already supported by most compilers.Ferrin
@Ayxan Concepts started as a TS; many compilers have worked on it several years ago. <format>, however, is mostly just the fmt library standardized.Cordoba
I came accross this post, searching for a different c++20 feature being supported and followed your link. The table changed a little, but Text formatting is still all red. @Tak Makoni: in case you use MSVC, here is a list of supported features per MSVC version: learn.microsoft.com/en-us/cpp/overview/…Horsepowerhour
Text formatting is now supported by GCC, Clang (partially), and MSVC. So this answer is outdated.Desecrate

© 2022 - 2024 — McMap. All rights reserved.