转自: 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
- package lm;
- message helloworld
- {
- 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
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());
}
#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