赞
踩
官网下载:https://github.com/google/protobuf
https://github.com/google/protobuf/releases
本人安装版本 protobuf-all-3.6.1.tar.gz
2.1 解压
tar zxvf protobuf-all-3.6.0.tar.gz
2.2 编译
cd protobuf-3.6.1/
./configure --prefix=/usr/local/protobuf(你的安装路径)
make
make check
make install
2.3 配置protobuf命令,更改环境变量:
vim /etc/profile
在文件的末尾添加如下的两行:
export PATH=$PATH:/usr/local/protobuf/bin/
export PKG_CONFIG_PATH=/usr/local/protobuf/lib/pkgconfig/
更改完成之后,执行如下命令立即执行:
source /etc/profile
这一步是必须的,如果少了这一步,会出现找不到protoc的命令错误。
2.4 配置动态链接库
vim /etc/ld.so.conf
在文件中添加
/usr/local/protobuf/lib(注意: 在新行处添加)
更改完成之后,执行如下命令立即执行:
sudo ldconfig
测试:
protoc --verison
看到对应版本信息,说明protobuf 安装成功
================================
编写简单例子
新建person.proto,内容如下
syntax="proto2"
package test;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
编译,生成C++代码
$ protoc ./person.proto --cpp_out=./
新建write_person.cpp 文件,代码如下
#include <iostream> #include <fstream> #include "person.pb.h" using namespace test; int main(){ Person p; p.set_name("test"); p.set_id(1); p.set_email("a.iabc.com"); std::string str; p.SerializeToString(&str); std::cout<<str<<std::endl; Person p1; p1.ParseFromString(str); std::cout<<"name:"<<p1.name()<<" email:"<<p1.email()<<std::endl; return 0; }
编译
g++ write_person.cpp person.pb.cc -g -o write_person -I/usr/local/protobuf/include -L/usr/local/protobuf/lib -lprotoc -lprotobuf -lpthread -std=c++11
例子2
新建 people.proto
syntax="proto2"; message People{ required string name = 1; required int32 age = 2; optional string email = 3; enum PhoneType{ MOBILE = 1; HOME = 2; WORK = 3; } message Phone{ required int32 id = 1; optional PhoneType type = 2 [default = HOME]; } repeated string phoneNum = 4; }
生成cpp 文件
protoc people.proto --cpp_out=./
新建write_file.cpp 文件
#include<iostream> #include "people.pb.h" #include<fstream> #include<string> using namespace std; int main() { string buffer; People people; people.set_name("chemical"); people.set_email("eiie@qq.com"); people.set_age(29); people.add_phonenum("abc"); people.add_phonenum("def"); fstream output("myfile",ios::out|ios::binary); people.SerializeToString(&buffer); output.write(buffer.c_str(),buffer.size()); return 0; }
编译 write_file.cpp 文件
g++ write_file.cpp people.pb.cc -g -o write_file -I/usr/local/protobuf/include -L/usr/local/protobuf/lib -lprotoc -lprotobuf -lpthread -std=c++11
新建读文件 read_file.cpp
#include <iostream> #include "people.pb.h" #include <fstream> #include <string> using namespace std; int main(){ People *people = new People; char buffer[BUFSIZ]; fstream input("myfile",ios::in|ios::binary); input.read(buffer,sizeof(People)); people->ParseFromString(buffer); cout << people->name() << people->phonenum(0) << endl; return 0; }
编译读文件
g++ read_file.cpp people.pb.cc -g -o read_file -I/usr/local/protobuf/include -L/usr/local/protobuf/lib -lprotoc -lprotobuf -lpthread -std=c++11
运行 ./read_file,输出
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。