最近想研究protobuf ,嘗試了很多次都沒有成功,我用的是ubuntu,在虛擬機下面的 ,protobuf 也用了很多版本但都沒有成功。最終用的是2.5.0版本才成功,話不多說直接開始梳理一下配置的流程。
首先得到 protobuf 相應的包文件 ,在終端上輸入如下
wget http://protobuf.googlecode.com/files/protobuf-2.5.0.tar.gz
下載完畢後進行解壓
tar zxvf protobuf-2.5.0.tar.gz
進入到解壓目錄
cd protobuf-2.5.0
進行執行
./configure
中間可能會出錯,估計是G++沒裝好,因爲安裝的時候要進行編譯
安裝G++
apt-get install g++
另外最好把Vim、make 也裝了,不然的後面的就很容易出問題,這些在其他教程上都沒提到過,是個人的一點經驗與大家分享一下
apt-get install vim
apt-get install make
./configure 成功之後,接下來 就如下幾步
make
make check
make install
安裝完成後在終端下執行
vim ~/.profile
打開配置文件,在該文件中添加
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
然後保存退出,接下來執行
source ~/.profile
是配置文件修改生效,最後執行
protoc --version
查看protobuf版本以測試是否安裝成功
接下來的操作 可以參照如下 鏈接 ,他們寫得非常好
http://www.ccvita.com/507.html
創建一個proto 文件 比如 msg.proto
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
對其代碼做了一些糾正
write cpp
#include "msg.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
using namespace lm;
int main(void)
{
lm:helloworld msg1;
msg1.set_id(101);
msg1.set_str("hello");
fstream output("./msg.pb",ios::out | ios::trunc | ios::binary);
if( !msg1.SerializeToOstream(&output))
{
cerr << "Failed to write msg." << endl;
return -1;
}
return 0;
}
reader.cpp
#include "msg.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
using namespace lm;
void listmsg(const lm::helloworld & msg)
{
cout << msg.id() <<endl;
cout << msg.str() <<endl;
}
int main(void)
{
lm:helloworld msg1;
fstream input("./msg.pb", ios::in | ios::binary);
if (!msg1.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
listmsg(msg1);
return 0;
}
Makefile
all: write reader
clean:
rm -f write reader msg.*.cc msg.*.h *.o log
proto_msg:
protoc --cpp_out=. msg.proto
write: msg.pb.cc write.cpp
g++ msg.pb.cc write.cpp -o write `pkg-config --cflags --libs protobuf`
reader: msg.pb.cc reader.cpp
g++ msg.pb.cc reader.cpp -o reader `pkg-config --cflags --libs protobuf`
如果提示 make: Nothing to be done for 'all
則執行make clean
如果從頭開始執行的話
1.make clean
2.make proto_msg
3.make
package demo;
message People
{ required string name = 1;
required int32 id = 2;
required string email = 3; }
demo::People p;
p.set_name("guoyilong");
p.set_id(i);
p.set_email("[email protected]");
p.SerializeToString(&data);
當 i = 0 裏 也就是 set_id(0)時 有一個很奇怪的現象,具體如下
data.length() 爲32
strlen(data.c_str()); 則爲 12 兩個結果不一致
而i 不等於0 則不會出現這種情況 現在還是不解 記錄一下