下载
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