1. Download the source code of protobuf from http://code.google.com/p/protobuf/downloads/list. Decompress, compile, and install the tool to use it. Installation steps are as follows: tar-xzf protobuf-2.1.0.tar.gz CD protobuf-2.1.0. /configure -- prefix =/usr/local/protobuf make check make install 2> sudo Vim/etc/profile add export Path = $ path: /usr/local/protobuf/bin/export pkg_config_path =/usr/local/protobuf/lib/pkgconfig/Save and execute source/etc/profile at the same time in ~ /. Add the above two lines of code to profile. Otherwise, the logon user cannot find the protoc command. 3> Configure the dynamic link library path sudo Vim/etc/lD. so. conf insert:/usr/local/protobuf/lib4> Su # Root permission ldconfig5> write message file: MSG. PROTO
package lm; message helloworld { required int32 id = 1; // ID required string str = 2; // str optional int32 opt = 3; //optional field }
Map the message file msg. proto to the CPP file protoc-I =. -- cpp_out =. msg. Proto. You can see that MSG. Pb. h and MSG. Pb. CC are generated.
6> write. CC
#include "msg.pb.h"#include <fstream>#include <iostream>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; }
Compile write. CC g ++ MSG. pb. CC write. CC-O write 'pkg-config -- cflags -- libs protobuf '-lpthread to execute write. /write. The log file is generated.
7> write deserialization process reader. CC
#include "msg.pb.h"#include <fstream>#include <iostream>using namespace std;void ListMsg(const lm::helloworld & msg) { cout << msg.id() << endl; cout << msg.str() << endl; } int main(int argc, char* argv[]) { lm::helloworld msg1; { fstream input("./log", ios::in | ios::binary); if (!msg1.ParseFromIstream(&input)) { cerr << "Failed to parse address book." << endl; return -1; } } ListMsg(msg1); }
Compile: G ++ msg. Pb. CC reader. CC-O reader 'pkg-config -- cflags -- libs protobuf'-lpthread execution./reader output: 101 Hello
8> write makefile
all: write readerclean: rm -f write reader msg.*.cc msg.*.h *.o logproto_msg: protoc --cpp_out=. msg.protowrite: msg.pb.cc write.cc g++ msg.pb.cc write.cc -o write `pkg-config --cflags --libs protobuf`reader: msg.pb.cc reader.cc g++ msg.pb.cc reader.cc -o reader `pkg-config --cflags --libs protobuf`