下载
注:访问外网会慢,用迅雷下载再传到你的服务器也是不错的方法
wget https://github.com/protocolbuffers/protobuf/releases/download/v21.8/protobuf-cpp-3.21.8.zip
安装
unzip protobuf-cpp-3.21.8.zip
cd protobuf-3.21.8
./configure --prefix=/usr
make
make check
sudo make install
sudo ldconfig
检查
有打印目录就是安装成功了
whereis protoc
which protoc
测试
test.proto文件
syntax = "proto2";
package common;
message MsgPerson
{
required uint32 ID = 1;
required uint32 age = 2;
required string name = 3;
required uint32 sex = 4;
}
将proto文件编译成 cpp文件
protoc -I=./ --cpp_out=./ ./test.proto
## 生成 test.pb.h, test.pb.cc
cpp代码:
test.cpp
#include<iostream>
#include "test.pb.h"
using namespace std;
int main()
{
common::MsgPerson buffInfo;
buffInfo.set_id(1);
buffInfo.set_age(27);
buffInfo.set_sex(1);
buffInfo.set_name("1024");
cout<<"++++++++++"<<endl;
cout<<"id:"<< buffInfo.id()<<endl;
cout<<"age:"<< buffInfo.age()<<endl;
cout<<"sex:"<< buffInfo.sex()<<endl;
cout<<"name:"<< buffInfo.name()<<endl;
return 0;
}
编译代码
g++ -o testproto ./test.cpp ./test.pb.cc -lprotobuf ## -lprotobuf必须要加,不然会报错,调用的函数未定义
./testproto