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

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

需要工具:

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

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

安装步骤:

  1. 下载源码 发布版地址
    以c++为例,下载最新的发布版 protobuf-cpp-3.14.0.zip
    wget https://github.com/protocolbuffers/protobuf/releases/download/v3.14.0/protobuf-cpp-3.14.0.zip
  2. 解压压缩包:
    unzip protobuf-cpp-3.14.0.zip
  3. 到源码目录.
    cd ~/protobuf-3.14.0
  4. 生成配置文件:
    ./autogen.sh
  5. 配置环境:
    ./configure
  6. 编译源码:
    make
  7. 安装:
    sudo make install
  8. 刷新动态库:
    sudo ldconfig

基本用例

  1. 定义你自己的消息,通过.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

  1. 生成源码,这里以C++为例:
  • 命令:
    protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto
  • 一个.proto文件会生成一个.h和一个.cc文件。 这里 addressbook.proto 生成了 addressbook.pb.h 和 addressbook.pb.cc
  1. 生成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): [email protected]
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):
  1. 解读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: [email protected]
  Work phone #: 01123456-999
  Updated: 2021-02-04T07:14:49Z


 

你可能感兴趣的:(C/C++,Linux,程序设计,ubuntu,linux,运维)