Ubuntu 下配置protobuf

来源:互联网 发布:2017电信诈骗数据 编辑:程序博客网 时间:2024/06/07 09:56

protobuf相比xml, json,节省内存空间,至于为什么,在这里就不探讨了。

上网下载源码protobuf-2.5.0.tar.gz (我使用的是这个版本,其他版本应该一样)

环境加ubuntu12.04


在安装该包前需要安装g++,make

apt-get install g++

apt-get intsall make


然后解压protobuf

tar zxvf protobuf-2.5.0.tar.gz  

cd protobuf-2.5.0

./configure   

make

make check

make install


安装完成后配置

vim ~/.profile

在文本最后添加如下内容

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

source ~/.profile

protoc --version

查看版本成功,则安装成功


proto buf的使用

首先创建一个msg.proto文件,内容如下

package lm;     message my_msg{         required int32     id = 1;  // ID           required string    str = 2;  // str          optional int32     opt = 3;  //optional field     }  


将msg.proto文件映射成.cpp文件

protoc -I=. --cpp_out=. msg.proto

这里在当前目前下会很成两个文件

msg.pb.cc  msg.pb.h


该生成文件的使用实例如下:

writer.cpp#include "msg.pb.h"  #include <iostream>  #include <fstream>  using namespace std;  using namespace lm;  int main(void)  {      lm:my_msg msg1;      msg1.set_id(100);      msg1.set_str("hello");      fstream output("./msg.pb",ios::out | ios::trunc | ios::binary);      if( !msg1.SerializeToOstream(&output))      {           cerr << "Failed to write msg." << endl;              return -1;        }      return 0;  }  

reader.cpp#include "msg.pb.h"  #include <iostream>  #include <fstream>  using namespace std;  using namespace lm;    void listmsg(const lm::helloworld & msg)  {      cout << msg.id() <<endl;      cout << msg.str() <<endl;  }    int main(void)  {      lm:msg_str msg1;      fstream input("./msg.pb", ios::in | ios::binary);         if (!msg1.ParseFromIstream(&input)) {                 cerr << "Failed to parse address book." << endl;                 return -1;         }         listmsg(msg1);      return 0;  }  

g++  msg.pb.cc write.cpp -o write  `pkg-config --cflags --libs protobuf`

g++  msg.pb.cc reader.cpp -o reader  `pkg-config --cflags --libs protobuf`

注意符号` 并不是单引号,而是1字旁边的符号


关于protobuf的好久,好后再说!



0 0