XML、JSON、ProtoBuf 都具有数据结构化和数据序列化的能力
XML、JSON 更注重数据结构化,关注人类可读性和语义表达能力。ProtoBuf 更注重数据序列化,关注效率、空间、速度,人类可读性差,语义表达能力不足(为保证极致的效率,会舍弃一部分元信息)
ProtoBuf 的应用场景更为明确,XML、JSON 的应用场景更为丰富。
linux下安装protobuf包
sudo ./configure
sudo make && make install
make编译时间有点长
Person.pro
syntax = "proto2"; //不添加会报警告错误
package demo;
message Person
{
//字段规则 类型 名称 编号
//required修饰字段 只能也必须出现1次
//repeated 字段可出现多次,包括0次
//optional 字段出现0次或1次
//类型:int32,int64,sint32,sint63,string, 32-bit...
required string name=1;
required int32 age=2;
optional string email=3;
}
在.profile中添加环境变量
#编译Person.pro
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
protoc --cpp_out=./ Person.pro
#生成如下几个文件
1.Person.pro.pb.h
2.Person.pro.pb.cc
Person.cc源文件demo
#include "Person.pro.pb.h"
#include <iostream>
using namespace std;
int main()
{
demo::Person per;
per.set_name("zhangsan");
per.set_age(20);
per.set_email("1549189372@qq.com");
//将消息格式化到字符串中
string in_data;
per.SerializeToString(&in_data);
cout<<"in_data format:"<<in_data<<endl;
//从字符串in_data进行解析
demo::Person decode_msg;
decode_msg.ParseFromString(in_data);
cout<<"name:"<<decode_msg.name()<<endl;
cout<<"age:"<<decode_msg.age()<<endl;
if (decode_msg.has_email())
{
cout<<"email:"<<decode_msg.email()<<endl;
}
}
#使用如下命令对源文件进行编译
g++ Person.cc Person.pro.pb.cc -o Person -lprotobuf
报如下错误信息:
dard. This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
#error This file requires compiler and library support
^
In file included from /usr/local/include/google/protobuf/stubs/common.h:52:0,
from Person.pro.pb.h:9,
from Person.cc:1:
/usr/local/include/google/protobuf/stubs/mutex.h:58:8: error: ‘mutex’ in namespace ‘std’ does not name a type
std::mutex mu_;
提示必须加上-std=c++11 or -std=gnu++11
g++ Person.cc Person.pro.pb.cc -o Person -std=c++11 -lprotobuf
报如下错误:
terminate called after throwing an instance of ‘std::system_error’
what(): Unknown error -1
Aborted (core dumped)
需要加上-lpthread
g++ Person.cc Person.pro.pb.cc -o Person -std=c++11 -lprotobuf
生成结果如下