欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Ubuntu20.04配置(五)编译安装protobuf

时间:2023-06-27

原文:编译安装protobuf 详细步骤 Ubuntu - 简书

需要工具:

autoconf, automake, libtool, make, g++, unzip

安装命令:
sudo apt-get install autoconf automake libtool make g++ unzip

安装步骤:

下载源码 发布版地址
以c++为例,下载最新的发布版 protobuf-cpp-3.14.0.zip
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.14.0/protobuf-cpp-3.14.0.zip解压压缩包:
unzip protobuf-cpp-3.14.0.zip到源码目录.
cd ~/protobuf-3.14.0生成配置文件:
./autogen.sh配置环境:
./configure编译源码:
make安装:
sudo make install刷新动态库:
sudo ldconfig基本用例 定义你自己的消息,通过.proto文件实现, 这里借用源码中的addressbook.proto

路径为:~/protobuf-3.14.0/examples/addressbook.proto

syntax = "proto3";package tutorial;import "google/protobuf/timestamp.proto";message Person { string name = 1; int32 id = 2; // Unique ID number for this person. string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { string number = 1; PhoneType type = 2; } repeated PhoneNumber phones = 4; google.protobuf.Timestamp last_updated = 5;}message AddressBook { repeated Person people = 1;}

标准类型如:string, int, doubule, 参考官方定义: https://developers.google.com/protocol-buffers/docs/proto3#scalar

生成源码,这里以C++为例:

命令:
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto一个.proto文件会生成一个.h和一个.cc文件。 这里 addressbook.proto 生成了 addressbook.pb.h 和 addressbook.pb.cc生成protobuf二进制文件(序列化)

编译:
g++ -std=c++11 add_person.cc addressbook.pb.cc -o add_person `pkg-config --cflags --libs protobuf`运行:

test@test:~/protobuf-3.14.0/examples$ ./add_person address_book.binaddress_book.bin: File not found、 Creating a new file.Enter person ID number: 123Enter name: JimEnter email address (blank for none): Jim.jim@google.comEnter a phone number (or leave blank to finish): 01123456-999Is this a mobile, home, or work phone? workEnter a phone number (or leave blank to finish):

解读protobuf二进制文件(反序列化)

编译:
g++ -std=c++11 list_people.cc addressbook.pb.cc -o list_people `pkg-config --cflags --libs protobuf`运行:

test@test:~/protobuf-3.14.0/examples$ ./list_people address_book.binPerson ID: 123 Name: Jim E-mail address: Jim.jim@google.com Work phone #: 01123456-999 Updated: 2021-02-04T07:14:49Z


 

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。