前段时间打算用下yaml,可惜的是,在把yaml-cpp链接到我的程序中时,一直提示我一堆错误,还好项目比较简单,就把程序的配置参数写到了txt文件中,然后手动解析。。。可是心里一直放不下yaml-cpp,最近总算有点闲空,折腾了半天,总算是能够成功使用yaml-cpp库了。
在编译我的程序时,出现了一堆错误,诸如 base operand of '->' is not a pointer: node& v = pMemory->create_node();
后来,编译时添加上了对c++11的支持,就没了这个问题,看来,最新的这个yaml-cpp 0.5.3用到了c++11新特性。
对于yaml语言,网上有很多教程,可以去搜索下,这里只是简单的讲下怎样在Linux 环境下使用yaml-cpp0.5,多说无益,直接看下下面的代码吧,仅是简单的使用的话,其实还是很容易的。
# yaml文件
subscribers:
- name: "Default task"
topic: "input/cmd_default_check"
timeout: 0.5
priority: 1
short_desc: "Default controller"
- name: "Navigation stack"
topic: "input/cmd_serial_navi"
timeout: 1.0
priority: 3
short_desc: "Navigation controller"
publisher: "output/cmd_vel"
------------------------------------------------------------------------------------------------------------------------------------------------------
//main.cpp文件
#include <iostream>
#include <fstream>
#include <string>
#include "yaml.h"
using namespace std;
//最新的yaml-cpp 0.5取消了运算符">>",但是还是会有好多的旧代码
//依旧在使用,所以重载下">>"运算符
template<typename T>
void operator >> (const YAML::Node& node, T& i)
{
i = node.as<T>();
}
void configure(const YAML::Node& node);
void nodePrint(const YAML::Node& node);
int main()
{
YAML::Node config = YAML::LoadFile("../cmd_mux.yaml");
configure(config["subscribers"]);
return 0;
}
void configure(const YAML::Node& node)
{
for (unsigned int i = 0; i < node.size(); i++)
{
nodePrint(node[i]);
}
}
void nodePrint(const YAML::Node& node)
{
string name;
string topic;
double timeout;
unsigned int priority;
node["name"] >> name;
node["topic"] >> topic;
node["timeout"] >> timeout;
node["priority"] >> priority;
cout<<" name: "<<name<<endl;
cout<<" topic: "<<topic<<endl;
cout<<" timeout: "<<timeout<<" seconds."<<endl;
cout<<"priority: "<<priority<<endl;
}
---------------------------------------------------------------------------------------------------------------------
CMakeLists.txt文件
cmake_minimum_required(VERSION 2.8)
project(test_yaml)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
link_directories(~/thz_libs/yaml-cpp-master/build)
include_directories(~/thz_libs/yaml-cpp-master/include/yaml-cpp)
add_executable(test main.cpp)
target_link_libraries(test yaml-cpp)
我在这里直接使用默认的/usr/lib里面的yaml-cpp,会出错,搜了下资料,大体意思是说可能电脑里有好多个版本的yaml-cpp,所以才会导致这种错误,我看了下,发现我电脑里果然有不同版本的yaml-cpp同时存在,所以这里我直接github上下载编译了最新的yaml-cpp 0.5.3,放在主文件目录下。