1、sudo apt-get install protobuf-compiler
2.编写简单proto文件
syntax = "proto2" ; //表明使用protobuf的编译器版本为v2,目前最新的版本为v3 namespace
{
optional string name = 1 ;
optional int32 age = 2 ;
optional int32 xxx = 3 ; //xxx 代表任意字段名称,为api 举例方便
}
message VehicleSignal {
enum TurnSignal {
TURN_NONE = 0 ;
TURN_LEFT = 1 ;
TURN_RIGHT = 2 ;
};
optional TurnSignal turn_signal = 1 ;
optional bool high_beam = 2 ;
optional bool low_beam = 3 ;
optional bool horn = 4 ;
optional bool emergency_light = 5 ;
}
3.编译
定义proto文件之后需要用protobuf提供的编译工具将proto文件编译成不同语言的源码,此处使用C++。
protoc -I=./ --cpp_out=./ test.proto
4.简单的测试代码
#include <stdio.h>
#include <iostream>
#include <string>
#include "test.pb.h"
using namespace std;
int main ( int argc, char * argv[])
{
Info * pinfo = new Info ();
pinfo-> set_name ( "testname" );
pinfo-> set_age ( 120 );
cout << "info.name=" << pinfo-> name () << ", age=" << pinfo-> age () << endl;
delete pinfo;
return 0 ;
}
5、g++ test_pb.cpp test.pb.cc -lprotobuf
6、./a.out
输出结果:
info.name=testname, age=120