要使用google proto buffer,首先要进行的就是安装,先说说我的(mac os X 10.7.2)安装过程吧:
1、下载google proto buff。
2、解压下载的包,并且阅读README.txt,根据里面的指引进行安装。
3、 $ ./configure
$ make
$ make check
$ make install
没有意外的话,前面三步应该都能顺利完成,第四步的时候,需要root权限。我采用的默认的路径,所以,仅仅用root权限,还是安装不了,要自己先在/usr/local下新建一个lib的目录,然后执行make install,这样,应该就能顺利安装google proto buffer了。
验证:
查看是否安装成功:protoc --version
如果出现:libprotoc 2.5.0 则说明安装成功!
如果出现错误:
protoc: error while loading shared libraries: libprotobuf.so.0: cannot open |
|
shared object file: No such file or directory |
The issue is that Ubuntu 8.04 doesn't include /usr/local/lib in |
|
library paths. |
|
To fix it for your current terminal session, just type in |
|
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib |
安装完后,先写一个测试程序来测试下安装,先来看看proto文件:
View Code package hello; message Hello{ required int32 id = 1; //user id required string name = 2; //user name optional string email = 3; //user email }
protoc hello.proto --cpp_out=./out
接下来,在out目录下,会生成两个文件:
$> ls
hello.pb.cc hello.pb.h
接下来,编写测试用的c++代码:
hello.cc #include <stdio.h> #include <string.h> #include "out/hello.pb.h" using namespace std; using namespace hello; int main() { Hello a; a.set_id(101); a.set_name("huangwei"); 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", b.id(), b.name().c_str()); } else { printf("decode faild!\n"); } return 0; }
g++ hello.cc ./out/hello.pb.cc -o hello -I./out -I/usr/local/protobuf/include -L/usr/local/lib -lprotobuf
这样,就生成了测试程序。
运行一下:
$> ./hello
encode success!
decode success!
id= 101
name = huangwei
这样,简单的google proto buffer的使用就完成了。有什么错误的地方,还请各位斧正。
转自: http://www.cnblogs.com/huangwei/archive/2012/01/16/2324108.html