编译库位置
ros环境的yaml会干扰正常环境,CMakeLists要修改下手动指定build文件夹下编译的库
CMakeLists.txt
cmake_minimum_required(VERSION 3.5) project(YamlCppExample) # 设置C++标准 set(CMAKE_CXX_STANDARD 11) # 查找yaml-cpp包 - ros 环境被干扰使用错误,报错段错误或者找不到 #find_package(yaml-cpp REQUIRED) # 添加可执行文件 add_executable(node main.cpp) # 链接yaml-cpp库 - ros 环境被干扰使用错误,报错段错误或者找不到 #target_link_libraries(node yaml-cpp) # 如果yaml-cpp没有自动发现,防止被ros环境干扰,手动找到编译的库位置: set(YAML_CPP_LIBRARIES "/home/dongdong/1sorftware/1work/openvslam/yaml-cpp-0.6.3/BUILD/libyaml-cpp.a") target_link_libraries(node ${YAML_CPP_LIBRARIES})
main.cpp
#include <iostream> #include <yaml-cpp/yaml.h> #include <fstream> using namespace std; int save_yaml(std::string sava_path) { // 创建一个YAML文档 YAML::Emitter emitter; // 开始写入YAML文档 emitter << YAML::BeginMap; emitter << YAML::Key << "name"; emitter << YAML::Value << "Alice"; emitter << YAML::Key << "age"; emitter << YAML::Value << 25; emitter << YAML::Key << "city"; emitter << YAML::Value << "London"; // 结束写入YAML文档 emitter << YAML::EndMap; // 将YAML数据写入文件 std::ofstream fout(sava_path); fout << emitter.c_str(); fout.close(); std::cout << "YAML data saved to output.yaml" << std::endl; return 0; } int read_yaml(std::string read_path) { try { // 读取YAML文件 YAML::Node config = YAML::LoadFile(read_path); // 访问YAML中的数据 std::string name = config["name"].as<std::string>(); int age = config["age"].as<int>(); std::string city = config["city"].as<std::string>(); // 打印读取的数据 std::cout << "Name: " << name << std::endl; std::cout << "Age: " << age << std::endl; std::cout << "City: " << city << std::endl; } catch (const YAML::Exception& e) { std::cerr << "YAML Exception: " << e.what() << std::endl; return 1; } return 0; } int main() { string config_path ="../config.yaml"; read_yaml(config_path); string sava_path ="../out.yaml"; save_yaml(sava_path) ; }
标签:std,12,YAML,yaml,include,cpp,ros From: https://www.cnblogs.com/gooutlook/p/18336388