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 

生成编译配置文件成功

运行配置脚本

扫描二维码关注公众号,回复: 10040670 查看本文章
./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,并能反序列化。

猜你喜欢

转载自www.cnblogs.com/WindSun/p/12543821.html