简体   繁体   English

通过 FetchContent 安装 protobuf 时如何使用 cmake 命令 protobuf_generate?

[英]How to I use the cmake command protobuf_generate when installing protobuf through FetchContent?

I am writing a client/server with gRPC.我正在使用 gRPC 编写客户端/服务器。 To generate the client/server protobuf code, I need to run the cmake command protobuf_generate .要生成客户端/服务器 protobuf 代码,我需要运行 cmake 命令protobuf_generate If I install protobuf beforehand, I have access to the command protobuf_generate .如果我事先安装了 protobuf,我可以访问命令protobuf_generate However, if I try to install protobuf with FetchContent :但是,如果我尝试使用FetchContent安装 protobuf:

cmake_minimum_required(VERSION 3.16)
project(ProtoObjects)

include(FetchContent)
set(FETCHCONTENT_QUIET OFF)
FetchContent_Declare(
  gRPC
  GIT_REPOSITORY https://github.com/grpc/grpc
  GIT_TAG        v1.49.2
  )
FetchContent_Declare(
    Protobuf
    GIT_REPOSITORY https://github.com/protocolbuffers/protobuf
    GIT_TAG        v21.12 
    SOURCE_SUBDIR  cmake
)
FetchContent_MakeAvailable(gRPC Protobuf)

add_library(
    proto-objects
        PUBLIC
            grpc++
)

target_include_directories(proto-objects PUBLIC "$<BUILD_INTERFACE:${PROTO_GENERATED_DIR}>")

protobuf_generate(
    TARGET proto-objects
    IMPORT_DIRS ${PROTO_IMPORT_DIRS}
    PROTOC_OUT_DIR ${PROTO_GENERATED_DIR}
)

protobuf_generate(
    TARGET proto-objects
    LANGUAGE grpc
    GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc
    PLUGIN "protoc-gen-grpc=\$<TARGET_FILE:gRPC::grpc_cpp_plugin>"
    IMPORT_DIRS ${PROTO_IMPORT_DIRS}
    PROTOC_OUT_DIR "${PROTO_GENERATED_DIR}"
)

I get the error:我收到错误:

Unknown CMake command "protobuf_generate".

How can I fix this error?我该如何解决这个错误?

In Protobuf version 21.12 and before the function protobuf_generate is defined in the protobuf-config.cmake script which is created upon installation.在 Protobuf 版本 21.12 和之前,函数protobuf_generate在安装时创建的protobuf-config.cmake脚本中定义。 Thus the function can be used only with already installed Protobuf, but not with the one included with FetchContent.因此,该函数只能用于已安装的 Protobuf,而不能用于 FetchContent 中包含的 Protobuf。

In the master (after that pull request ) the function protobuf_generate is defined in the script cmake/protobuf-generate.cmake , so that script can be included even in the build tree (after FetchContent):在 master 中(在pull request之后)函数protobuf_generate在脚本cmake/protobuf-generate.cmake中定义,因此脚本甚至可以包含在构建树中(在 FetchContent 之后):

...
FetchContent_MakeAvailable(Protobuf)

# Get source directory of the Protobuf
FetchContent_GetProperties(Protobuf SOURCE_DIR Protobuf_SOURCE_DIR)
# Include the script which defines 'protobuf_generate'
include(${Protobuf_SOURCE_DIR}/cmake/protobuf-generate.cmake)

...
protobuf_generate(...)


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM