ubuntu16.04下yaml-cpp的安装和使用

因为项目需要配置系统文件,想到了要用yaml。但是,yaml-cpp安装和使用过程中遇到了一些问题,调了两天终于调通了。把经验记录下来,希望有需要的人能少走些弯路。

1. 安装:

坑1:一定要 0.5.2版本, 我之前下载的0.5.3版本 汇报错 核心段错误.

从官方git源https://github.com/jbeder/yaml-cpp/releases/tag/release-0.5.2下载 tar.gz的源码包,按照以下步骤做:

cd yaml-cpp # 进入克隆的文件夹

mkdir build

cd build

cmake -DBUILD_SHARED_LIBS=ON ..

make

sudo make install

坑2:make完一定要make install,如果想自己cp的话,也一定要cp到 /usr/local/lib 和 /usr/local/include 文件夹下,而不是/usr/lib 和 /usr/include 文件夹,否则会找不到 库 找不到 yaml.h 文件。

2.使用:

yaml-cpp 5.0版本以后的使用有了改变

5.0版本之前:


	1.  YAML::Parser parser(fin);
	2.  YAML::Node doc;
	3.  parser.GetNextDocument(doc);

5.0版本之后 没有GetNextDocument函数了。而是使用


	1.  YAML::Node doc = YAML::Load(fin);

 3.测试代码:

1.CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project(test_yaml)


find_package(Boost REQUIRED COMPONENTS system)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

find_package(PkgConfig)
pkg_check_modules(NEW_YAMLCPP yaml-cpp>=0.5)
if(NEW_YAMLCPP_FOUND)
add_definitions(-DHAVE_NEW_YAMLCPP)
endif(NEW_YAMLCPP_FOUND)


link_directories(
    /usr/lib/
    )

include_directories(
    include
    yaml-cpp
)

add_executable(test ./src/main.cpp)
target_link_libraries(test ${catkin_LIBRARIES} yaml-cpp)

 

//main.cpp文件
#include <iostream>
#include <fstream>
#include <string>
#include "yaml-cpp/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("../src/test.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;
}   


  return 0;
}

3.test.yaml

 

# 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"

 

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值