CentOS7安裝protobuf(C++)和簡單使用


下載 protobuf

下載地址

使用wget下載,或者手動下載好FTP傳到Linux上

在Linux 64位環境下進行編譯

我下載的是protobuf-all-3.11.4.tar.gz 包

首先解壓

tar zxvf protobuf-all-3.11.4.tar.gz

進入解壓目錄

cd protobuf-3.11.4/

安裝 protobuf

此時可能會遇到報錯,如:autoreconf: command not found

則說明需要安裝幾個軟件

sudo yum install autoconf 
sudo yum install automake 
sudo yum install libtool

以上安裝成功后再次執行

./autogen.sh 

生成編譯配置文件成功

運行配置腳本

./configure

make

sudo    #輸入密碼
make  #要編譯很久
make check    #測試
make install    #安裝

查看版本

protoc --version    #查看版本

在這里插入圖片描述
注:新版本不需要執行autogen.sh腳本,直接./configure就行,./configure不用添加--prefix,默認位置就在/usr/local/

簡單使用protobuf

創建一個.proto文件:addressbook.proto,內容如下

syntax = "proto3";
package IM;
message Account {
    //賬號
    uint64 ID = 1;
    //名字
    string name = 2;
    //密碼
    string password = 3;
}

message User {
    Account user = 1;
}

編譯.proto文件,生成C++語言的定義及操作文件

protoc --cpp_out=. Account.proto

生成的文件:Account.pb.h, Account.pb.cc
在這里插入圖片描述
編寫程序main.cpp

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

using namespace std;

int main(int argc, char** argv)
{
    IM::Account account1;
    account1.set_id(1);
    account1.set_name("windsun");
    account1.set_password("123456");

    string serializeToStr;
    account1.SerializeToString(&serializeToStr);
    cout <<"序列化后的字節:"<< serializeToStr << endl;


    IM::Account account2;
    if(!account2.ParseFromString(serializeToStr))
    {
        cerr << "failed to parse student." << endl;
        return -1;
    }
    cout << "反序列化:" << endl;
    cout << account2.id() << endl;
    cout << account2.name() << endl;
    cout << account2.password() << endl;

    google::protobuf::ShutdownProtobufLibrary();

    return 0;
}

編譯

g++ main.cpp Account.pb.cc -o main -lprotobuf -std=c++11 -lpthread

注:程序使用protobuf,編譯沒有問題,運行時一到建立protobuf對象就崩潰,搜索了半天沒找到原因,后來偶然看到以前正常使用的makefile文件中后面加了-lpthread,加上就好了。我自己的程序沒有用到多線程,應該是protobuf3里面用到了。

運行
在這里插入圖片描述
可以看到能正常序列化到string,並能反序列化。
注:如果出現了錯誤

error while loading shared libraries: libprotobuf.so.22: cannot open shared object file: No such file or directory

方法1:請執行export LD_LIBRARY_PATH=/usr/local/lib
方法2:root用戶編輯/etc/ld.so.conf中加入/usr/local/lib這一行,保存之后,再運行ldconfig更新一下配置即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM