google protobuf 在Linux下安装与使用

来源:互联网 发布:慈溪市司法拍卖淘宝网 编辑:程序博客网 时间:2024/06/05 04:28

一、介绍

     首先,protobuf是一个开源项 目,而且是后台很硬的开源项目。网上现有的大部分(至少80%)开源项目,要么是某人单干、要么是几个闲杂人等合伙搞。而protobuf则不然,它是 鼎鼎大名的Google公司开发出来,并且在Google内部久经考验的一个东东。由此可见,它的作者绝非一般闲杂人等可比。
  那这个听起来牛X的东东到底有啥用处捏?简单地说,这个东东干的事儿其实和XML 差不多,也就是把某种数据结构的信息,以某种格式保存起来。主要用于数据存储、传输协议格式等场合。有同学可能心理犯嘀咕了:放着好好的XML不用,干嘛重新发明轮子啊?!先别急,后面俺自然会有说道。
  话说到了去年(大约是08年7月),Google突然大发慈悲,把这个好东西贡献给了开源社区。这下,像俺这种喜欢捡现成的家伙可就有福啦!貌似喜欢 捡现成的家伙还蛮多滴,再加上 Google的号召力,开源后不到一年,protobuf的人气就已经很旺了。

二、安装

1、下载protobuf源码包

2、解压安装

root@ubuntu:/opt/protobuf-2.5.0# ./configure...root@ubuntu:/opt/protobuf-2.5.0#make...root@ubuntu:/opt/protobuf-2.5.0# make check...root@ubuntu:/opt/protobuf-2.5.0# make install       //need root permission

3、默认的安装路径是/usr/local/include和/usr/local/lib里面,所以要设置一下编译加载库的默认环境变量,如果不设置会提示找不到动态库。

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
三、使用示例

1、写一个简单的hello.proto文件,定义数据的类型

package hello;message Hello{required int32 id = 1;required string name = 2;optional string email = 3;}
2、创建一个out目录,输出protoc 格式化后的.cc文件和.h文件

root@ubuntu:/media/work/test/protobuf# protoc hello.proto --out_cpp=./out //以C++方式输出
3、然后在out目录下会生成两个文件

4、编写简单C++程序编解码测试

/*hello.cpp*/#include <cstdio>#include <cstring>#include "out/hello.pb.h"using namespace std;using namespace hello;int main(){    Hello a;    a.set_id(101);    a.set_name("kiqin");a.set_email("769232001@qq.com");    string tmp;    bool ret = a.SerializeToString(&tmp);    if (ret)    {        printf("encode success!\n");    }    else    {        printf("encode faild!\n");    }    Hello b;    ret = b.ParseFromString(tmp);    if (ret)    {        printf("decode success!\n id= %d \n name = %s\n email = %s\n", b.id(), b.name().c_str(), b.email().c_str());    }    else    {        printf("decode faild!\n");    }    return 0;}
5、为了方便编译,写一个makefile管理

CC = g++TARGET = helloCFALGS = -Wall -g -I./out -I/usr/local/includeLDFLAGS = -L/usr/local/libLIBS = -lprotobufOBJ = hello.o hello.pb.o$(TARGET):$(OBJ)$(CC) $(CFLAGS) $(LDFLAGS) $(LIBS) -o $@ $^hello.o:hello.cpp$(CC) -c $(CFLAGS) $(LDFLAGS) $(LIBS) -o $@ $<hello.pb.o:./out/hello.pb.cc$(CC) -c $(CFLAGS) $(LDFLAGS) $(LIBS) -o $@ $<clean:rm -fr *.o $(TARGET)
附protobuf-2.5.0源码包:

http://download.csdn.net/detail/codeheng/8365443



1 0
原创粉丝点击