c++ 開發(fā)中如何讀寫yaml配置文件
c++ 開發(fā)中利用yaml-cpp讀寫yaml配置文件
1、yaml-cpp 是一個開源庫,地址在 github 上,https://github.com/jbeder/yaml-cpp。
在ubuntu中可以輸入git clone https://github.com/jbeder/yaml-cpp
獲取yaml-cpp源碼。
2、進入到y(tǒng)aml-cpp目錄,新建一個build目錄。
3、進入到build目錄,輸入cmake -D BUILD_SHARED_LIBS=ON …編譯出動態(tài)庫。
4、創(chuàng)建自己測試用的文件夾,將yaml-cpp目錄下面的include 目錄拷貝到測試目錄下,將編譯后的動態(tài)庫也拷貝到測試目錄下,同事目錄下在編寫三個文件,分別為CMakeLists.txt、config.yaml、main.cpp。
main.cpp內容如下:
#include <iostream> #include "include/yaml-cpp/yaml.h" using namespace std; int main(int argc,char** argv) { YAML::Node config = YAML::LoadFile("../config.yaml"); cout << "name:" << config["name"].as<string>() << endl; cout << "sex:" << config["sex"].as<string>() << endl; cout << "age:" << config["age"].as<int>() << endl; return 0; }
config.yaml內容如下:
name: xiaoyu sex: man age: 20
CMakeLists.txt內容如下:
cmake_minimum_required(VERSION 3.2) project(yaml_test) add_definitions(-std=c++11) include_directories(include) set(SRCS main.cpp) add_executable(yamltest ${SRCS}) target_link_libraries(yamltest ${CMAKE_HOME_DIRECTORY}/libs/libyaml-cpp.so)
5、在當前目錄創(chuàng)建 build 文件夾,然后進入 build 文件執(zhí)行 cmake 操作。
mkdir build cd build cmake ..
特別說明:
編譯過程中如遇到:
關于 CMake Error: CMake Error: The source directory …does not appear to contain CMakeLists.txt.這個問題時,只需要復制一下終端報錯內容中的CMakeLists.txt對自己所寫的cmake文件重新命名,編譯就可以啦。
到此這篇關于c++ 開發(fā)中讀寫yaml配置文件的文章就介紹到這了,更多相關c++ yaml配置文件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!