std::string_view represents a constant string that doesn’t have to be null-terminated. Unlike std::string, it doesn’t store a copy of the original string but only its location. This class is typically implemented with two pointers or with a pointer and an integer.

std::string_view was officially introduced in the C++ standard library with C++17. The Arduino core from ESP32 comes with an old version of GCC that doesn’t support C+17, so we cannot use std::string_view on ESP32. Or can we?

Even if std::string_view only came out officially with C++17, it was in the boxes for a long time. GCC 5.2, the compiler used for ESP32, comes with an experimental version std::string_view that we can use with ArduinoJson.

Disclaimer

The workaround presented here is very hackish and goes against recommended practices. It is only acceptable because it is a temporary solution until the compiler gets upgraded.

This article was written for version 1.0.6 of the core; please adapt to the version installe on your machine.

To use use std::string_view on ESP32, we must:

  1. recreate the <string_view> header from <experimental/string_view>
  2. import std::experimental::string_view into the std namespace
  3. set ARDUINOJSON_ENABLE_STRING_VIEW to 1
  4. change the flag -std=gnu++11 to -std=gnu++1y

Steps 1 and 2

For the two first steps, locate the standard library folder. On Windows, it’s currently:

%LOCALAPPDATA%\Arduino15\packages\esp32\tools\xtensa-esp32-elf-gcc\1.22.0-97-gc752ad5-5.2.0\xtensa-esp32-elf\include\c++\5.2.0

In this folder, create a file named string_view (without extension) with the following content:

#include "experimental/string_view"
namespace std { using std::experimental::string_view; }

Step 3

For the third step, you simply need to add the following block at the beginning of your program:

#define ARDUINOJSON_ENABLE_STRING_VIEW 1
#include <ArduinoJson.h>

Step 4

Step 4 requires that you change the compiler flags in platform.txt. On Windows, this file is currently located here:

%LOCALAPPDATA%\Arduino15\packages\esp32\hardware\esp32\1.0.6\platform.txt

In this file, locate the line that starts with compiler.cpp.flags= and replace -std=gnu++11 with -std=gnu++17 (it’ literally a one-character change). You don’t need to restart the Arduino IDE after modifying this file.

Test

You should now be able to use std::string_view. Use the following program to test you setup:

#define ARDUINOJSON_ENABLE_STRING_VIEW 1
#include <ArduinoJson.h>

void setup() {
  Serial.begin(115200);

  StaticJsonDocument<128> doc;
  doc[std::string_view("hello!", 5)] = std::string_view("world!", 5);

  serializeJson(doc, Serial);  // prints {"hello":"world"}
}

void loop() {
}
 X online