1.2在Ubuntu环境中,以C++代码编译为例,操作步骤如下:

 

1.2.1.protobuf编译器(protoc)安装:

在build protobuf之前,先安装几个工具

$sudo apt-get install autoconf automake libtool curl make g++ unzip

 

从github下载源码包

git clone http://github.com/protocolbuffers/protobuf.git

cd protobuf

git submodule update –init –recursive

./autogen.sh

 

build和install c++ protobuf运行环境和编译器(protoc),其中make步骤比较慢,耐心等待

./configure

make

make check

sudo make install

sudo ldconfig # refresh shared library cache

protoc --version

如果make check 失败,依然可以继续安装,但是有些功能将不工作。执行完最后一步,窗口会相应protoc的版本,如下图所示。

 

Ubuntu下使用Protocol Buffer(简写:protobuf) (1.2-1.3环境测试)

 

1.3环境测试

打开protobuf下examples文件夹,可以看到一个addressbook.proto文件,这是google提供的样例。

Ubuntu下使用Protocol Buffer(简写:protobuf) (1.2-1.3环境测试)

执行以下命令,将addressbook.proto转换出addressbook.pb.cc 和addressbook.pb.h文件

$protoc addressbook.proto --cpp_out=./

 

也可以将addressbook.pb.cc 和addressbook.pb.h生成到指定的目录中,

$ protoc -I=/路径1 --cpp_out=./路径2 /路径1/addressbook.proto

路径1为.proto所在的路径

路径2为.cc和.h生成的位置

 

会看到目录下多出addressbook.pb.cc 和addressbook.pb.h文件

Ubuntu下使用Protocol Buffer(简写:protobuf) (1.2-1.3环境测试)

将 addressbook.proto、addressbook.pb.cc 、addressbook.pb.h、add_person.cc 、list_people.cc这5个文件单独放入一个文件夹01_test,在vs code中打开。

 

Ubuntu下使用Protocol Buffer(简写:protobuf) (1.2-1.3环境测试)

从add_person.cc代码中可以看出,是将自己输入的信息 序列化为一个文件,从list_people.cc代码中可以看出是将文件反序列化,并输出到Terminal。在addressbook.pb.cc文件中提供了许多API

1.3.1在terminal中运行程序(add_person.cc序列化)

$ g++ add_person.cc addressbook.pb.cc `pkg-config --cflags --libs protobuf`

会生成一个a.out文件

$./a.out pb.txt

其中pb.txt是用来存放序列化后的信息,文件名字可以自己定义。

Ubuntu下使用Protocol Buffer(简写:protobuf) (1.2-1.3环境测试)

 

1.3.2在terminal中运行程序(list_people.cc反序列化)

$ g++ list_people.cc addressbook.pb.cc `pkg-config --cflags --libs protobuf`

$./a.out pb.txt

会在terminal看到刚才输入的信息

Ubuntu下使用Protocol Buffer(简写:protobuf) (1.2-1.3环境测试)

 

*可能会遇到的坑…

执行proto3文件,必须将protoc版本更新到3.0以上。protoc版本3.0以上可以编译protoc2和protoc3,但是protoc版本2.0是无法编译proto3的,只能编译proto2。

 

之前还遇到一个“open …..”的错误,后来把g++更新到7.0版本就解决了

 

相关文章:

  • 2022-12-23
  • 2021-11-25
  • 2021-12-27
  • 2022-12-23
  • 2022-02-26
  • 2022-12-23
  • 2021-05-24
猜你喜欢
  • 2021-04-07
  • 2021-05-09
  • 2021-10-05
  • 2021-07-04
  • 2021-11-15
  • 2022-12-23
  • 2021-07-09
相关资源
相似解决方案