linux前置条件

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

最新包proto3 git下载地址,找到自己对应的语言
https://github.com/protocolbuffers/protobuf/releases/latest

编译protoc

  1. ./autogen.sh
  2. ./configure
  3. make
  4. sudo make install

如果想用已经编译好的,下载protoc开头的zip包就好

Mac下的方法更简单

  1. brew install

使用方法

写一个简单的tutorial.proto

  1. syntax = "proto3";
  2. package tutorial;
  3. message Test1 {
  4. int32 a = 1;
  5. }
  1. protoc simple.proto --cpp_out=.
  2. protoc simple.proto --python_out=.
  3. protoc simple.proto --java_out=.
  4. protoc simple.proto --js_out=.
  5. protoc simple.proto --js_out=.
  1. #include <iostream>
  2. #include <fstream>
  3. #include "tutorial.pb.h"
  4. using namespace std;
  5. int main(int argc, char const *argv[])
  6. {
  7. tutorial::Test1 t1;
  8. t1.set_a(150);
  9. cout << "t1.a = " << t1.a() << endl;
  10. std::string message;
  11. t1.SerializeToString(&message);
  12. fstream f;
  13. f.open("/tmp/pbuf", ios::out | ios::binary);
  14. if(!f.is_open()) {
  15. cout << "CANNOT OPEN /tmp/pbuf" << endl;
  16. }
  17. f << message;
  18. f.close();
  19. tutorial::Test1 t2;
  20. t2.ParseFromString(message);
  21. cout << "t2.a = " << t2.a() << endl;
  22. return 0;
  23. }

编译一下看看

  1. g++ tutorial.pb.cc main.cc -std=c++11 $(pkg-config --libs protobuf)

编码方式
00000000: 0896 01