qtgrpcgen 工具
qtgrpcgen
工具可用于从 protobuf 模式生成Qt GRPC 服务类。该工具由 CMakeQt6::GrpcTools
软件包提供。它是对 Googleprotoc
工具的扩展。
find_package(Qt6 COMPONENTS GrpcTools REQUIRED)
使用方法
Qt XML 提供的 CMake 函数可简化qtgrpcgen
工具的使用。将 CMake 用作编译工具时,最好使用Qt CMake API。对于 CMake 以外的编译系统,您可以手动调整运行 qtgrpcgen 中列出的命令。
注意: 没有明确支持使用 gRPC™Qt GRPC 和 Protobuf 应用程序的明确支持。
CMake
以下 CMake 命令将gRPC 服务集成到 Qt 项目中。
使用 Protobuf 模式生成基于 Qt 的 C++ 服务 |
通常qtgrpcgen
会通过 CMake 使用qt_add_grpc
宏调用,如下例所示:
cmake_minimum_required(VERSION 3.16...3.22) project(MyProject) find_package(Qt6 REQUIRED COMPONENTS Protobuf Grpc) qt_standard_project_setup() qt_add_executable(MyApp main.cpp) qt_add_protobuf(MyApp PROTO_FILES path/to/messages.proto ) qt_add_grpc(MyApp CLIENT PROTO_FILES path/to/service.proto ) target_link_libraries(MyApp PRIVATE Qt6::Protobuf Qt6::Grpc)
上例调用了qt_add_grpc()
CMake 函数,开始为所提供的 protobuf 模式中的service
部分生成Qt GRPC 代码。
注意: 如果 protobuf 模式还包含message
定义,则也应调用qt_add_protobuf()
CMake 函数来启动Qt Protobuf 代码生成。
由于我们重复使用了可执行目标,所有生成的文件都将附加到目标中,包含目录也将相应更新。
手动运行qtgrpcgen
protoc --plugin=protoc-gen-qtgrpc=<path/to/bin/>qtgrpcgen \ --qtgrpc_out="[<options>:]<output_dir>" \ [--qtgrpc_opt="<options>"] \ [-I/extra/proto/include/path] \ <protofile>.proto
options
参数是一个以分号分隔的选项列表。可以将options
添加到--qtgrpc_out
参数中,用冒号分隔,也可以通过单独的参数--qtgrpc_opt
来传递。也可以通过QT_GRPC_OPTIONS
环境变量传递相应的键值。键值必须以分号分隔的列表形式出现:
export QT_GRPC_OPTIONS="COPY_COMMENTS;GENERATE_PACKAGE_SUBFOLDERS"
选项
生成器支持可用于调整生成的选项。选项在qt_add_grpc函数中有直接别名。支持以下选项:
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
根据项目结构选择首选的保护方式。
QML
可生成 服务的 QML 客户端。gRPC
© 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.