ubuntu安装protobuf

下载

复制代码
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.19.4/protobuf-all-3.19.4.tar.gz

安装

bash 复制代码
tar zxvf protobuf-all-3.19.4.tar.gz		//解压
cd protobuf-3.19.4/						//进入解压目录
//检查并安装以下环境,本次使用centos7环境,Ubuntu使用apt-get安装。
sudo apt install autoconf 
sudo apt install automake 
sudo apt install libtool
//以上安装成功后执行下面
./autogen.sh
//生成编译配置文件成功,运行配置脚本
./configure
make  				//要编译很久
make check    		//测试
make install    	//安装

sudo ldconfig        //刷新动态库权限,否则即使安装成功系统也无法识别

测试

查看protoc版本

bash 复制代码
protoc --version    //查看版本

代码测试

首先编写proto文件

cpp 复制代码
syntax = "proto3";
package IM;
message Account {
    //账号
    uint64 ID = 1;
    //名字
    string name = 2;
    //密码
    string password = 3;
}
 
message User {
    Account user = 1;
}

生成代码

cpp 复制代码
protoc --cpp_out=./ myAccount.proto
cpp 复制代码
#include <iostream>
#include <fstream>
#include "myAccount.pb.h"
 
using namespace std;
 
int main(int argc, char** argv)
{
    IM::Account account1;
    account1.set_id(1);
    account1.set_name("ysl");
    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;
}

编译运行

bash 复制代码
g++ main.cpp myAccount.pb.cc myAccount.pb.h -o main -lprotobuf -std=c++11 -lpthread -Bstatic
相关推荐
未济3 天前
linux 配置环境变量
linux
傲世仙尊3 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
_艾伦 耶格尔.3 天前
进程间通信
linux
AI职业加油站3 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
Liuqy-053 天前
Linux IO编程——静态库、动态库
linux
此冬歌咏3 天前
K8s 节点故障实战:优雅驱逐 31 秒,硬故障 331 秒,以及那个永远 Pending 的 Pod
运维·k8s
彧azz3 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
-梅3 天前
linux(8) 软硬链接
linux·运维·服务器
AIgorithmGEEK3 天前
[Linux]线程三部曲(上):一个执行流的诞生——从操作系统一路拆到 pthread_create
linux·线程·pid