一、protobuf安装
1、下载protobuf安装包
https://github.com/google/protobuf.git
2、解压
3、执行autogen.sh
4、配置
./configure
5、编译
make
6、安装
make install
最后执行
ldconfig # refresh shared library cache.
二、使用
1、编写test.proto文件
syntax="proto3";
message Person{
string name=1;
int32 id=2;
string email=3;
enum PhoneType{
MOBILE=0;
HOME=1;
WORE=2;
}
message PhoneNumber{
string number=1;
PhoneType type=2;
}
repeated PhoneNumber phones=4;
}
message AddressBook{
Person people=1;
}
~
~
~
2、对proto文件编译生成.cpp文件和.h文件
sudo protoc --cpp_out=. test.proto
3、创建编写test_proto.cpp文件,测试
#include <iostream>
#include "test.pb.h"
using namespace std;
int main() {
Person test;
test.set_id(1);
test.set_name("herry");
test.set_email("herry@qq.com");
//Person::PhoneType phonetype;
Person::PhoneNumber phone_num;
phone_num.set_number("12345");
//phone_num.set_type(Person::WORK);
cout<<"id: "<<test.id()<<endl;
cout<<"name: "<<test.name()<<endl;
cout<<"email: "<<test.email()<<endl;
cout<<"phone number: "<<phone_num.number()<<endl;
cout<<"phone type: "<<phone_num.type()<<endl;
return 0;
}
编译输出结果如下所示: