Working with YAML in C++: the yaml-cpp library
YAML (YAML Ain't Markup Language) is a human-readable data serialization format that is often used for configuration files, data exchange, and storing structured information. In C++, there is a powerful and easy-to-use library yaml-cpp for working with YAML. In this article, we will take a detailed look at how to install, configure, and use yaml-cpp for parsing and creating YAML documents.
Installing yaml-cpp
The yaml-cpp library is available for most platforms. The easiest way to install it is via a package manager:
- Ubuntu/Debian:
sudo apt-get install libyaml-cpp-dev - macOS (Homebrew):
brew install yaml-cpp - Windows (vcpkg):
vcpkg install yaml-cpp
You can also build it from source by cloning the repository from GitHub and using CMake:
git clone https://github.com/jbeder/yaml-cpp.gitcd yaml-cppmkdir build && cd buildcmake ..makesudo make installBasics of working with yaml-cpp
The library provides an intuitive API for loading, modifying, and saving YAML data. All data types are stored in the YAML::Node container, which can be a scalar, a sequence (array), or a mapping (dictionary).
Example YAML file
Consider the following configuration file config.yaml:
database: host: localhost port: 5432 name: myapp credentials: user: admin password: secret123
server: workers: 4 timeout: 30.5 debug: true
allowed_ips: - 192.168.0.1 - 192.168.0.2 - 10.0.0.1Parsing a YAML file
To load data from a file, the YAML::LoadFile() function is used:
#include <yaml-cpp/yaml.h>#include <iostream>#include <string>#include <vector>
int main() { try { // Load the YAML file YAML::Node config = YAML::LoadFile("config.yaml");
// Access nested data using the [] operator std::string host = config["database"]["host"].as<std::string>(); int port = config["database"]["port"].as<int>(); std::string user = config["database"]["credentials"]["user"].as<std::string>();
std::cout << "Database host: " << host << std::endl; std::cout << "Database port: " << port << std::endl; std::cout << "User: " << user << std::endl;
// Working with a sequence (list) YAML::Node ips = config["allowed_ips"]; std::vector<std::string> ipList; for (const auto& ip : ips) { ipList.push_back(ip.as<std::string>()); }
std::cout << "Allowed IPs: "; for (const auto& ip : ipList) { std::cout << ip << " "; } std::cout << std::endl;
} catch (const YAML::Exception& e) { std::cerr << "YAML Error: " << e.what() << std::endl; return 1; }
return 0;}Creating and serializing YAML
yaml-cpp also allows you to create YAML documents programmatically and save them to a file:
#include <yaml-cpp/yaml.h>#include <fstream>
int main() { // Create a root node YAML::Node config;
// Add data config["application"]["name"] = "MyApp"; config["application"]["version"] = 2.1; config["application"]["debug"] = false;
// Create a sequence config["features"].push_back("logging"); config["features"].push_back("caching"); config["features"].push_back("auth");
// In