Download Protobuffer
$wget http://protobuf.googlecode.com/files/protobuf-2.5.0.tar.gz
unzip
$tar xvzf protobuf-2.5.0.tar.gz
intstall
$./configure
$make
$make check
$make install
$vim ./profile
add
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
$source ./profile
$protoc --version
run a example
vim lm.helloworld.proto
i
package lm;
message helloworld{
required int32 id=1;//ID
required string str=2;//str
optional int32 opt=3;//optional field
}
然后生成对应的cpp和h文件
protoc lm.helloworld.proto // --cpp_out=./out
#include "lm.helloworld.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
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;
}
$g++ Writer.cpp lm.helloworld.pb.cc `pkg-config --cflags --libs protobuf` -o writer
$vim Reader.cpp
#include "lm.helloworld.pb.h"
#include <fstream>
#include <iostream>
using namespace std;
void ListMsg(lm::helloworld &msg){
cout<<msg.id()<<endl;
cout<<msg.str()<<endl;
}
int main(){
lm::helloworld msg1;
{
fstream input("./log",ios::in|ios::binary);
if(!msg1.ParseFromIstream(&input)){
cerr<<"Failed to parse addresss book."<<endl;
return -1;
}
}
ListMsg(msg1);
}
$g++ Reader.cpp lm.helloworld.pb.cc `pkg-config --cflags --libs protobuf` -o reader
$./writer
$./reader