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/technique/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 
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章