qtprotobufgen 工具
qtprotobufgen
工具可用于从 protobuf 模式生成Qt Protobuf 类。该工具由 CMakeQt6::ProtobufTools
软件包提供。它是对 Googleprotoc
工具的扩展。
find_package(Qt6 COMPONENTS ProtobufTools REQUIRED)
使用方法
Qt XML 提供的 CMake 函数可简化qtprotobufgen
工具的使用。将 CMake 用作编译工具时,您应优先使用Qt CMake API。对于 CMake 以外的编译系统,请调整手动运行中描述的命令。
注意: 没有明确支持使用 gRPC™Qt GRPC 和 Protobuf 应用程序的明确支持。
CMake
以下 CMake 命令将 protobuf 模式集成到 Qt 项目中。
使用 protobuf 模式生成基于 Qt 的 C++ 源代码 |
通常qtprotobufgen
会通过 CMake 使用qt_add_protobuf
宏调用。
使用 qt_add_protobuf
cmake_minimum_required(VERSION 3.16...3.22) project(MyThings) find_package(Qt6 REQUIRED COMPONENTS Protobuf) qt_standard_project_setup() qt_add_protobuf(MyMessages GENERATE_PACKAGE_SUBFOLDERS PROTO_FILES path/to/message.proto path/to/other_message.proto PROTO_INCLUDES /path/to/proto/include ) qt_add_executable(MyApp main.cpp) target_link_libraries(MyApp PRIVATE MyMessages)
在上面的例子中,我们生成了一个名为MyMessages
的库,其中包含了PROTO_FILES
选项传递的路径中定义的消息类型。GENERATE_PACKAGE_SUBFOLDERS
选项用于为生成的文件生成文件夹结构。PROTO_INCLUDES
选项告诉 protoc 在指定目录中查找依赖项或导入项。我们创建了一个名为MyApp
的可执行文件目标,并将其链接到MyMessages
库。
手动运行
protoc --plugin=protoc-gen-qtprotobuf=<path/to/bin/>qtprotobufgen \ --qtprotobuf_out="[<options>:]<output_dir>" \ [--qtprotobuf_opt="<options>"] \ [-I/extra/proto/include/path] \ <protofile>.proto
options
参数是一个以分号分隔的选项列表。有两种不同的传递方式。一种是在 output_dir 参数的选项前加上冒号分隔。或者通过一个单独的参数--qtprotobuf_opt
。也可以通过QT_PROTOBUF_OPTIONS
环境变量传递相应的键值。键值需要以分号分隔的列表形式呈现:
export QT_PROTOBUF_OPTIONS="COPY_COMMENTS;GENERATE_PACKAGE_SUBFOLDERS"
选项
生成器支持可用于调整生成的选项。选项在qt_add_protobuf函数中有直接别名。支持以下选项:
COPY_COMMENTS
将 文件中的注释复制到生成的代码中。.proto
GENERATE_PACKAGE_SUBFOLDERS
使用 文件中的软件包名称指定符来创建生成文件的文件夹结构。例如,如果软件包定义为,生成的文件将放在.proto
package io.qt.test
OUTPUT_DIRECTORY/io/qt/test/ 目录中。EXPORT_MACRO
定义生成代码中使用的导出宏的基本名称。最终宏名的构造为 。如果未设置该选项,则不会生成导出宏。QPB_<EXPORT_MACRO>_EXPORT
自 Qt 6.8 起,支持以下格式:
EXPORT_MACRO=macro_name[:macro_output_file[:<true|false>]]
.该格式允许您指定包含导出宏的头文件的名称,并明确控制是否生成导出宏。注意: 如果未提供<macro_output_file>,该选项默认使用以前的语法。
HEADER_GUARD
指定用于防止生成的头文件被多重包含的机制。可能的值是 , 。默认值为 。将该选项设置为 会生成现代 pragma 头文件防护机制:pragma
filename
filename
pragma
#pragma once ...
省略该选项或将该选项设置为
filename
会生成ifdef
封装保护,并使用".proto "文件名作为保护后缀:#ifdef MYMESSAGES_QPB_H #define MYMESSAGES_QPB_H ... #endif // MYMESSAGES_QPB_H
根据项目结构选择首选的保护方式。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.