Working with YAML in C++: yaml-cpp and rapidyaml libraries
YAML (YAML Ain't Markup Language) is a data serialization format widely used for configuration files, environment description files (Docker Compose, Kubernetes), and for data exchange between services. Unlike JSON, YAML is more human-readable thanks to indentation and support for comments.
C++ has no built-in YAML support, but excellent third-party libraries exist. In this article, we will look at the two most popular ones: yaml-cpp (classic, simple) and rapidyaml (modern, very fast). You will learn how to install the libraries, read a YAML file, create one programmatically, and handle typical errors.
1. yaml-cpp Library
yaml-cpp is the de facto standard library for working with YAML in C++. It provides a convenient API reminiscent of working with STL containers. The library supports the YAML 1.2 specification.
Installation
The easiest way is to use the vcpkg or Conan package manager. For Linux/macOS:
# Installation via vcpkgvcpkg install yaml-cpp
# Installation via Conanconan install yaml-cpp/0.7.0@If you prefer to build manually, download the source code from GitHub and run:
mkdir build && cd buildcmake ..cmake --build .sudo cmake --install .Parsing a YAML File
Suppose we have a configuration file config.yaml:
server: host: "localhost" port: 8080 debug: true
database: driver: "postgresql" connection_string: "host=localhost dbname=test" pool_size: 10Example of reading and accessing data in C++:
#include <yaml-cpp/yaml.h>#include <iostream>#include <string>
int main() { try { // Loading the file YAML::Node config = YAML::LoadFile("config.yaml");
// Accessing nested nodes std::string host = config["server"]["host"].as<std::string>(); int port = config["server"]["port"].as<int>(); bool debug = config["server"]["debug"].as<bool>();
std::cout << "Server: " << host << ":" << port << " (debug=" << (debug ? "on" : "off") << ")";
// Checking if a key exists if (config["database"]["pool_size"]) { int pool = config["database"]["pool_size"].as<int>(); std::cout << "Pool size: " << pool << ""; }
// Iterating over a sequence (list) // Suppose the YAML has a field: hosts: ["alpha", "beta", "gamma"] // for (const auto& h : config["hosts"]) { // std::cout << "Host: " << h.as<std::string>() << ""; // }
} catch (const YAML::Exception& e) { std::cerr << "YAML parsing error: " << e.what() << ""; return 1; } catch (const std::exception& e) { std::cerr << "General error: " << e.what() << ""; return 1; } return 0;}Creating a YAML Document
With yaml-cpp, you can not only read but also generate YAML:
#include <yaml-cpp/yaml.h>#include <fstream>
int main() { YAML::Emitter out; out << YAML::BeginMap; out << YAML::Key << "application"; out << YAML::Value << "MyApp"; out << YAML::Key << "version"; out << YAML::Value << 2.5; out << YAML::Key << "features"; out << YAML::Value << YAML::BeginSeq; out << "logging" << "auth" << "cache"; ou