欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > linux protobuf的安装与使用

linux protobuf的安装与使用

2025/6/23 8:47:16 来源:https://blog.csdn.net/ckg3824278/article/details/144240409  浏览:    关键词:linux protobuf的安装与使用

  首先,下载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

觉得有帮助的话,打赏一下呗。。

           

需要商务合作(定制程序)的欢迎私信!! 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词