Linux安装protobuf(C++)和简单使用(亲测可用)
下载protobuf
protobuf下载链接
第一步:下载
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.19.4/protobuf-all-3.19.4.tar.gz
第二步:安装
tar zxvf protobuf-all-3.19.4.tar.gz
cd protobuf-3.19.4/
sudo yum install autoconf
sudo yum install automake
sudo yum install libtool
./autogen.sh
./configure
make
make check
make install
第三步:安装成功
protoc --version
简单使用protobuf
关于protobuf的介绍参考:Protobuf介绍 完成序列化和反序列化,本实验目录在:/home/admin/Learn_MyProtobuf 创建一个.proto文件:myAccount.proto,内容如下
syntax = "proto3";
package IM;
message Account {
uint64 ID = 1;
string name = 2;
string password = 3;
}
message User {
Account user = 1;
}
编译.proto文件,生成C++语言的定义及操作文件
protoc -I=/home/admin/Learn_MyProtobuf --cpp_out=/home/admin/Learn_MyProtobuf /home/admin/Learn_MyProtobuf/myAccount.proto
生成的文件:myAccount.pb.h, myAccount.pb.cc
编写程序main.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;
}
对main.cpp进行编译
g++ main.cpp myAccount.pb.cc myAccount.pb.h -o main -lprotobuf -std=c++11 -lpthread -Bstatic
编译过程中可能出现如下问题: error while loading shared libraries: libprotobuf.so.30: cannot open shared object file: No such file 如果按照我上面的protobuf按照步骤,一般是因为安装路径没有加入到配置中所以报错,否则还是重新安装一遍吧。 按照上面的步骤安装的protobuf,它的库在如下位置:
/usr/local/lib
最好写到/etc/profile中,然后 source /etc/profile 一下
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
此时运行程序:
./main
得到结果:
|