YAML-CPP

yaml作为一种便捷的文件格式,通过C++进行操作时,可以利用yaml-cpp进行。

一、yaml-cpp的安装

  1. 下载源代码
git clone https://github.com/jbeder/yaml-cpp.git
  1. 编译安装
mkdir build
cd build
cmake -DBUILD_SHARED_LIBS=ON ..    # ON 设置生成共享库
sudo make install
  1. 验证
pkg-config --modversion yaml-cpp

二、使用

YAML::Node node1 = YAML::LoadFile("config.yaml");    // 加载文件
YAML::Node node2 = YAML::Load("[1,2,3]");        // 加载数组
cout << node1[0].as<string>() << endl;
cout << node2[0].as<int>() << endl;        // 输出元素

更多API参考yaml-cpp docs

三、示例工程

  1. CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(yaml_test)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
link_directories(/home/jonty/Softwares/yaml-cpp/build)
include_directories(/home/jonty/Softwares/yaml-cpp/include/yaml-cpp)
add_executable(test main.cpp)
target_link_libraries(test yaml-cpp) 
  1. main.cpp
#include <iostream>
#include "yaml.h"
using namespace std;
int main()
{
	YAML::Node node = YAML::Load("[22,3,4,4]");
	cout << node[0] << endl;
	YAML::Node node2 = YAML::LoadFile("../config.yaml");
	cout << node2["ttt"] << endl;
	return 0;
}
  1. 编译运行
mkdir build
cd build
cmake ..
make 
./test

参考教程
tutorials

posted @ 2018-10-11 06:27  Jonty  阅读(6779)  评论(0编辑  收藏  举报