首先,下载protobuf:
wget https://github.com/protocolbuffers/protobuf/releases/download/v21.11/protobuf-cpp-3.21.11.zip
然后,解压:
tar -xf protobuf-2.5.0.tar.gz
接着,安装protobuf
cd protobuf-3.21.11/
mkdir build
./configure --prefix=$PWD/build
make -j8
make check
make install
验证:
cd build/bin/
./protoc --version
使用:
1)定义.proto文件(contacts.proto)
syntax = "proto3";
package contacts;message PeopleInfo {string name = 1;int32 age = 2;
}
2)用protoc
编译器编译.proto文件
protoc --cpp_out=. contacts.proto
3)使用生成的API
#include <iostream>
#include <fstream>
#include <string>
#include "contacts.pb.h"int main()
{// Create a PeopleInfo messagecontacts::PeopleInfo person;person.set_name("John Doe");person.set_age(30);// Serialize to filestd::string filename = "person.bin";std::ofstream output(filename, std::ios::binary);if (!person.SerializeToOstream(&output)) {std::cerr << "Failed to write person." << std::endl;return -1;}output.close();// Read from file and deserializecontacts::PeopleInfo person2;std::ifstream input(filename, std::ios::binary);if (!person2.ParseFromIstream(&input)) {std::cerr << "Failed to read person." << std::endl;return -1;}// Verify the datastd::cout << "Name: " << person2.name() << std::endl;std::cout << "Age: " << person2.age() << std::endl;return 0;
}
4)编译
g++ main.cpp contacts.pb.cc -o main -L../lib/ -lprotobuf -I../include
5)运行
./main
觉得有帮助的话,打赏一下呗。。
需要商务合作(定制程序)的欢迎私信!!