首先安装Protobuf编译器和库,然后编写.proto文件定义消息格式,接着使用protoc生成C++代码,再在程序中包含头文件并调用序列化与反序列化接口,最后编译时链接Protobuf库即可完成整个流程。

在C++中使用Protocol Buffers(简称Protobuf)需要经过几个步骤:定义消息格式、生成C++代码、编译链接库以及在程序中序列化和反序列化数据。以下是详细使用方法。
1. 安装Protobuf编译器和库
首先确保系统中安装了protoc编译器和对应的C++库。
以Ubuntu为例:
- sudo apt-get install protobuf-compiler # 安装protoc
- sudo apt-get install libprotobuf-dev # 安装C++开发库
macOS用户可用Homebrew:
立即学习“C++免费学习笔记(深入)”;
- brew install protobuf
2. 编写.proto文件定义消息结构
创建一个person.proto文件,定义一个简单的消息类型:
syntax = "proto3";message Person { string name = 1; int32 age = 2; string email = 3; }
3. 使用protoc生成C++代码
运行以下命令生成C++源文件:
95Shop可以免费下载使用,是一款仿醉品商城网店系统,内置SEO优化,具有模块丰富、管理简洁直观,操作易用等特点,系统功能完整,运行速度较快,采用ASP.NET(C#)技术开发,配合SQL Serve2000数据库存储数据,运行环境为微软ASP.NET 2.0。95Shop官方网站定期开发新功能和维护升级。可以放心使用! 安装运行方法 1、下载软件压缩包; 2、将下载的软件压缩包解压缩,得到we
protoc --cpp_out=. person.proto
会生成两个文件:person.pb.h 和 person.pb.cc,它们包含了Person类的定义。
4. 在C++项目中使用生成的类
包含头文件并使用Person类进行序列化与反序列化。
示例代码:
#include#include #include "person.pb.h" int main() { // 设置调试日志(可选) GOOGLE_PROTOBUF_VERIFY_VERSION;
// 创建一个Person对象 Person person; person.set_name("Alice"); person.set_age(30); person.set_email("alice@example.com");
// 序列化到文件 std::ofstream output("person.data", std::ios::binary); if (!person.SerializeToOstream(&output)) { std::cerr << "Failed to write person data." << std::endl; return -1; } output.close();
// 从文件反序列化 Person person2; std::ifstream input("person.data", std::ios::binary); if (!person2.ParseFromIstream(&input)) { std::cerr << "Failed to read person data." << std::endl; return -1; } input.close();
// 打印结果 std::cout << "Name: " << person2.name() << std::endl; std::cout << "Age: " << person2.age() << std::endl; std::cout << "Email: " << person2.email() << std::endl;
// 清理全局资源(可选) google::protobuf::ShutdownProtobufLibrary(); return 0; }
5. 编译和链接
编译时需要链接Protobuf库:
g++ -std=c++11 main.cpp person.pb.cc -lprotobuf -o demo
如果使用CMake,可以在CMakeLists.txt中添加:
find_package(Protobuf REQUIRED)
include_directories(${Protobuf_INCLUDE_DIRS})
target_link_libraries(your_target ${Protobuf_LIBRARIES})
基本上就这些。只要定义好.proto文件,用protoc生成代码,再正常调用set_、serialize、parse等接口即可。注意处理I/O错误和版本兼容性。不复杂但容易忽略初始化和清理步骤。









