linux下安装protobuf教程+示例(详细)

转自: http://www.cppblog.com/colorful/archive/2012/05/05/173761.html , 并稍加修改。

1. 在网站 http://code.google.com/p/protobuf/downloads/list上可以下载 Protobuf 的源代码。然后解压编译安装便可以使用它了。
安装步骤如下所示:
 tar -zxvf protobuf-2.5.0.tar.gz
 cd protobuf-2.5.0
 ./configure --prefix=/usr/local/protobuf
 make 
 make check 
 make install 
 
2> sudo vim /etc/profile
 添加
export PATH=$PATH:/usr/local/protobuf/bin/
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/protobuf/lib/pkgconfig/
保存执行
source /etc/profile
同时 在~/.profile中添加上面两行代码,否则会出现登录用户找不到protoc命令

3 > 配置动态链接库路径
sudo vim /etc/ld.so.conf
插入:
/usr/local/protobuf/lib

4 > su  #root 权限
ldconfig

5> 写消息文件:msg.proto
  1. package lm;   
  2. message helloworld   
  3. {   
  4.     required int32     id = 1;  // ID     
  5.     required string    str = 2;  // str    
  6.     optional int32     opt = 3;  //optional field   
  7. }  
将消息文件msg.proto映射成cpp文件
protoc -I=. --cpp_out=. msg.proto
可以看到生成了msg.pb.h 和msg.pb.cc

6> 测试代码
#include "msg.pb.h"
#include <stdio.h>
#include <iostream>
using namespace std;

int main(){
        lm::helloworld msg1;
        msg1.set_id(101);
        msg1.set_str("hello");
        string str;
        msg1.SerializeToString(&str);
        printf("%s\n" , str.c_str());

        lm::helloworld msg2;
        msg2.ParseFromString(str);
        printf("id %d str %s\n" , msg2.id() , msg2.str().c_str());
}

编译:g++  msg.pb.cc reader.cc -o reader  `pkg-config --cflags --libs protobuf` -lpthread

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值