protobuf for C++: 完整指南与示例

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

什么是 Protocol Buffers (protobuf) 以及为什么需要它?

\n\n

Protocol Buffers (protobuf) 是一种由 Google 开发的强大、高效且可扩展的结构化数据序列化机制。它允许您在一个特殊文件(.proto)中定义数据结构一次,然后生成用于读取和写入这些数据的各种编程语言(C++、Java、Python、Go 等)的源代码。

\n\n

为什么需要 protobuf?

\n
    \n
  • 高效性: Protobuf 将数据序列化为二进制格式,该格式比 XML 或 JSON 等文本格式更紧凑且处理速度更快。这对于高负载系统和微服务架构尤其重要。
  • \n
  • 速度: 数据的序列化和反序列化速度比传统文本格式快一个数量级。
  • \n
  • 类型安全: 生成的代码提供强类型检查,从而减少运行时错误的数量。
  • \n
  • 跨平台与多语言支持: 您可以定义一次数据模式,并在 C++、Python、Java 和其他语言的项目中使用它。
  • \n
  • 向后兼容性: Protobuf 支持数据模式的演进:您可以添加新字段,而不会破坏旧版本的应用程序。
  • \n
\n\n

为 C++ 安装 protobuf

\n\n

要在 C++ 中使用 protobuf,您需要安装两样东西:protoc 编译器(将 .proto 文件转换为 C++ 代码)和 protobuf 的 C++ 库本身。

\n\n

1. 安装 protoc 编译器

\n

最简单的方法是从 protobuf 在 GitHub 上的官方发布页面 下载预编译的二进制文件。

\n
# Linux 示例 (Ubuntu/Debian)\nsudo apt-get install protobuf-compiler\n\n# macOS 示例 (通过 Homebrew)\nbrew install protobuf\n\n# 对于 Windows,请下载 protoc-x.x.x-win64.zip 并将 protoc.exe 的路径添加到 PATH 环境变量中
\n\n

2. 安装 protobuf 的 C++ 库

\n

建议从源代码构建库或使用包管理器。

\n
# Ubuntu/Debian\nsudo apt-get install libprotobuf-dev\n\n# macOS (Homebrew)\nbrew install protobuf\n\n# 从源代码构建(通用方法)\ngit clone https://github.com/protocolbuffers/protobuf.git\ncd protobuf\ngit submodule update --init --recursive\nmkdir build && cd build\ncmake -DCMAKE_BUILD_TYPE=Release -Dprotobuf_BUILD_TESTS=OFF ..\nmake -j$(nproc)\nsudo make install
\n\n

3. 配置 CMake 项目(推荐方法)

\n

将以下内容添加到您的 CMakeLists.txt 中:

\n
find_package(Protobuf REQUIRED)\ninclude_directories(${Protobuf_INCLUDE_DIRS})\n\n# 自动编译 .proto 文件\nfile(GLOB PROTO_FILES "*.proto")\nprotobuf_generate_cpp(PROTO_SRCS PROTO_HDRS ${PROTO_FILES})\n\nadd_executable(my_program main.cpp ${PROTO_SRCS})\ntarget_link_libraries(my_program ${Protobuf_LIBRARIES})
\n\n

快速入门与代码示例

\n\n

让我们创建一个简单的示例来演示基础知识。我们将为联系人定义一个数据结构。

\n\n

步骤 1:创建 .proto 文件

\n

文件 contact.proto:

\n
syntax = "proto3";\n\npackage tutorial;\n\nmessage Person {\n  string name = 1;\n  int32 age = 2;\n  string email = 3;\n}
\n\n

步骤 2:生成 C++ 代码

\n
protoc --cpp_out=. contact.proto
\n

执行命令后,将生成 contact.pb.h 和 contact.pb.cc 文件。

\n\n

步骤 3:编写 C++ 代码

\n

文件 main.cpp:

\n
#include <iostream>\n#include <fstream>\n#include "contact.pb.h"\n\nusing namespace std;\n\nint main() {\n    // 确保库已初始化\n    GOOGLE_PROTOBUF_VER                    

推荐