下载
git clone https://github.com/google/protobuf.git
cd protobuf
$ ./autogen.sh
可能会遇到以下问题:/autogen.sh: 40: autoreconf: not found
解决办法: sudo apt-get install autoconf automake libtool
./configure –prefix=/usr
make
make check
make install
使用
一、首先定义一个proto文件:
package lm;
message helloworld
{
required int32 id = 1; // ID
required string str = 2; // str
optional int32 opt = 3; //optional field
}
取名为:lm.helloworld.proto
在该文件的当前目录下,运行如下命令:
protoc -I=./ --cpp_out=./ lm.helloworld.proto
生成lm.helloworld.pb.h 和 lm.helloworld.pb.cc两个文件,分别是类的定义和实现文件。
二、然后使用上面两个文件,新建write.cpp和read.cpp文件:
write.cpp
#include "lm.helloworld.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
lm::helloworld msg1;
msg1.set_id(101);
msg1.set_str("Hello");
fstream output("./log", ios::out | ios::trunc | ios::binary);
if (!msg1.SerializeToOstream(&output))
{
cerr << "Failed to write msg." << endl;
return -1;
}
return 0;
}
read.cpp
#include "lm.helloworld.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
lm::helloworld msg1;
fstream input("./log", ios::in | ios::binary);
if (!msg1.ParseFromIstream(&input))
{
cerr << "Failed to parse address book." << endl;
return -1;
}
cout << msg1.id() << endl;
cout << msg1.str() << endl;
return 0;
}
三、编译上面两个文件
c++ write.cpp lm.helloworld.pb.cc -lprotobuf -o write
c++ read.cpp lm.helloworld.pb.cc -lprotobuf -o read