Download
git clone https://github.com/google/protobuf.git
CD Protobuf
$./autogen.sh
You may experience the following issues:/autogen.sh:40:autoreconf:not found
workaround: sudo apt-get install autoconf automake libtool
./configure–prefix=/usr
Make
Make check
Make install use
First, define a proto file:
Package LM;
Message HelloWorld
{
required int32 id = 1; ID
Required String str = 2; Str
optional int32 opt = 3; Optional field
}
Named as: Lm.helloworld.proto
In the current directory of the file, run the following command:
protoc-i=./--cpp_out=./Lm.helloworld.proto
Generate Lm.helloworld.pb.h and lm.helloworld.pb.cc two files, respectively, for the class definition and implementation file.
Second, then use the above two files, create a new write.cpp and Read.cpp file:
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 the parse address Book." << Endl;
return-1;
}
cout << msg1.id () << Endl;
cout << msg1.str () << Endl;
return 0;
}
Third, compile the above two files
c++ write.cpp Lm.helloworld.pb.cc-lprotobuf-o write C + + read.cpp lm.helloworld.pb.cc- Lprotobuf-o Read