How to use C++17 / C++23 with PlatformIO using ESP32 / Arduino

Problem:

By default, PlatformIO uses -std=gnu++11 as a compiler flag but you want to use C++17 or C++23 features.

If you just use

build_flags = -std=gnu++17

this will lead to g++ being called with g++ ... -std=gnu++17 ... -std=gnu++11 ... compiler flags. The latter one – gnu++11 i.e. C++11 will take precedence.

Solution:

In order to activate C++17, use

build_flags = -std=gnu++17
build_unflags = -std=gnu++11

In order to activate C++23 (not fully implemented yet in G++), you currently need to use -std=gnu++2a:

build_flags = -std=gnu++2a
build_unflags = -std=gnu++11