Google Protobuf的安装、配置、以及简单demo编译

【准备工作】
 

【前提
我是以root用户的身份来登录的,非root用户可以su命令登录root帐号,或者在需要权限的命令前面加sudo。

【安装】
假设下载的是protobuf-2.1.0.tar.gz
     
tar -zxvf protobuf-2.1.0.tar.gz 
cd protobuf-2.1.0 
./configure --prefix=/opt /protobuf    (这里指定的路径可以是任意 )
make
make check 
make install
 

【配置】
1、环境变量(方法可以有很多种,这里我修改的是/etc/profile)
vim /etc/profile
    
加入以下部分
PROTOBUF_HOME=/opt/protobuf
PROTOBUF_PKG_CONFIG_PATH=${PROTOBUF_HOME}/lib/pkgconfig

export data-path="${PATH}:${PROTOBUF_HOME}/bin:"
export PKG_CONFIG_data-path="${PKG_CONFIG_PATH}:${PROTOBUF_PKG_CONFIG_PATH}"

在~/.profile中添加上面两行export代码,否则上面两行export不会生效。
    
2 、动态链接库路径
vim /etc/ld.so.conf
添加这行
/opt/protobuf/lib
    
为了让动态链接库修改生效
ldconfig   ( ldconfig命令的作用见     http://www.xxlinux.com/linux/article/accidence/tec hnique/20081230/14754.html  )

【简单的demo编译
1、写pb文件(消息文件)
msg.proto

package test;   
message msg   
{   
    required int32     id = 1;     
    required string    str = 2;   
    optional int32     opt = 3;  
}
   
2、pb文件 转换成cpp文件
protoc -I=. --cpp_out=. msg.proto  (java或者python的话,第二个参数不一样,这里是针对cpp )
生成了 msg.pb.h 和msg.pb.cc

3、 写序列化消息的进程
writer.cc

#include "msg.pb.h"  
#include <fstream>  
#include <iostream>  

using namespace std;  
  
int main(void)   
{   
    test::msg obj;   
    obj.set_id(101);   
    obj.set_str("hello");   
    fstream output("./log", ios::out | ios::trunc | ios::binary);   
  
    if (!obj.SerializeToOstream(&output)) {   
        cerr << "Failed to write msg." << endl;   
        return -1;   
    }          
    return 0;   
}  
 
编译 writer.cc 
g++  msg.pb.cc writer.cc -o writer  `pkg-config --cflags --libs protobuf` -lpthread

./writer   ,   会在本地生成log文件

4、写反序列化的进程
reader.cc

#include "msg.pb.h"  
#include <fstream>  
#include <iostream>  

using namespace std;  
  
void PrintMsg(const test::msg & obj) {    
    cout << obj.id() << endl;   
    cout << obj.str() << endl;   
}   
  
int main(int argc, char* argv[]) {   
    test::msg obj;     
    {   
        fstream input("./log", ios::in | ios::binary);   
        if (!obj.ParseFromIstream(&input)) {   
            cerr << "Failed to parse address book." << endl;   
            return -1;   
        }         
    }    
    PrintMsg(obj);   
}  

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

./reader 
输出 :
101
hello

5、Makefile
all : writer reader  

clean :  
    rm -f writer reader msg.*.cc msg.*.h *.o  log  

proto_msg :  
    protoc --cpp_out=. msg.proto  

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

reader : msg.pb.cc reader.cc  
    g++  msg.pb.cc reader.cc -o reader  `pkg-config --cflags --libs protobuf` 
 
【结束


Allen Lin
2013/06/26 
    
原文地址:https://www.cnblogs.com/bbsno1/p/3270942.html