sudo apt-get install autoconf automake libtool curl make g++ unzip ./configure --prefix=/home/work/tool/protobuf-3.18.0-install sudo make sudo make check(可忽略) sudo make install
进入bin目录,可以看到编译出来的protoc,这个工具是用来将.proto编译成目标语言的序列化代码
创建工程
include 目录是上面编译出来的,直接拷贝过来
libprotobuf.a 是上面编译出来的lib目录下的静态库
msg.proto 自定义数据结构,定义如下
package Im;
message Content
{
required int32 id = 1;
required string str = 2;
optional int32 opt = 3;
}
接下来就可以将msg.proto编译出c++代码,使用的工具就是上面编译出来的bin目录下的文件
~/work/tool/protobuf-3.19.0-install/bin/protoc --cpp_out=./ msg.proto
编译后生成两个文件
#include编写反序列化demo#include #include "msg.pb.h" //演示了将数据机构序列化 保存到./log文件中 //g++ -o main main.cpp msg.pb.cc -Iinclude -L. -lprotobuf int main() { Im::Content msg1; msg1.set_id(123); msg1.set_opt(465); msg1.set_str("hello world"); std::fstream output("./log",std::ios::out|std::ios::trunc|std::ios::binary); if(!msg1.SerializeToOstream(&output)) { std::cerr << "err output!" << std::endl; return -1; } return 0; }
#include执行结果#include #include "msg.pb.h" //g++ -o deserialize deserialize.cpp msg.pb.cc -Iinclude -L. -lprotobuf int main() { Im::Content msg; std::fstream input("./log",std::ios::in|std::ios::binary); if(!msg.ParseFromIstream(&input)) { std::cerr << "parse err!" << std::endl; return -1; } std::cout << "" << msg.id() << std::endl; std::cout << "" << msg.str() << std::endl; return 0; }



