栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

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

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.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.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


 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/733636.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号