protobuf 安装和使用

淩亂°似流年 2022-08-10 09:26 312阅读 0赞

下载

git clone https://github.com/google/protobuf.git
cd protobuf
$ ./autogen.sh

  1. 可能会遇到以下问题:/autogen.sh: 40: autoreconf: not found
  2. 解决办法: sudo apt-get install autoconf automake libtool

./configure –prefix=/usr
make
make check
make install

使用

一、首先定义一个proto文件:

  1. package lm;
  2. message helloworld
  3. {
  4. required int32 id = 1; // ID
  5. required string str = 2; // str
  6. optional int32 opt = 3; //optional field
  7. }

取名为:lm.helloworld.proto
在该文件的当前目录下,运行如下命令:

  1. protoc -I=./ --cpp_out=./ lm.helloworld.proto

生成lm.helloworld.pb.h 和 lm.helloworld.pb.cc两个文件,分别是类的定义和实现文件。

二、然后使用上面两个文件,新建write.cpp和read.cpp文件:
write.cpp

  1. #include "lm.helloworld.pb.h"
  2. #include <iostream>
  3. #include <fstream>
  4. using namespace std;
  5. int main(void)
  6. {
  7. lm::helloworld msg1;
  8. msg1.set_id(101);
  9. msg1.set_str("Hello");
  10. fstream output("./log", ios::out | ios::trunc | ios::binary);
  11. if (!msg1.SerializeToOstream(&output))
  12. {
  13. cerr << "Failed to write msg." << endl;
  14. return -1;
  15. }
  16. return 0;
  17. }

read.cpp

  1. #include "lm.helloworld.pb.h"
  2. #include <iostream>
  3. #include <fstream>
  4. using namespace std;
  5. int main(void)
  6. {
  7. lm::helloworld msg1;
  8. fstream input("./log", ios::in | ios::binary);
  9. if (!msg1.ParseFromIstream(&input))
  10. {
  11. cerr << "Failed to parse address book." << endl;
  12. return -1;
  13. }
  14. cout << msg1.id() << endl;
  15. cout << msg1.str() << endl;
  16. return 0;
  17. }

三、编译上面两个文件

  1. c++ write.cpp lm.helloworld.pb.cc -lprotobuf -o write
  2. c++ read.cpp lm.helloworld.pb.cc -lprotobuf -o read

发表评论

表情:
评论列表 (有 0 条评论,312人围观)

还没有评论,来说两句吧...

相关阅读