Ubuntu20.04配置(五)编译安装protobuf
·
原文:编译安装protobuf 详细步骤 Ubuntu - 简书
需要工具:
- autoconf, automake, libtool, make, g++, unzip
安装命令:sudo apt-get install autoconf automake libtool make g++ unzip
安装步骤:
- 下载源码 发布版地址
以c++为例,下载最新的发布版 protobuf-cpp-3.14.0.zipwget 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.bin
address_book.bin: File not found. Creating a new file.
Enter person ID number: 123
Enter name: Jim
Enter email address (blank for none): Jim.jim@google.com
Enter a phone number (or leave blank to finish): 01123456-999
Is this a mobile, home, or work phone? work
Enter 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.bin
Person ID: 123
Name: Jim
E-mail address: Jim.jim@google.com
Work phone #: 01123456-999
Updated: 2021-02-04T07:14:49Z
更多推荐
已为社区贡献2条内容
所有评论(0)