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

2023-11-30

我正在使用 gRPC 编写客户端/服务器。要生成客户端/服务器 protobuf 代码,我需要运行 cmake 命令protobuf_generate。如果我事先安装了 protobuf,我就可以访问该命令protobuf_generate。但是,如果我尝试安装 protobufFetchContent:

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}"
)

我收到错误:

Unknown CMake command "protobuf_generate".

我该如何修复这个错误?


在 Protobuf 21.12 版本及之前的函数中protobuf_generate定义在protobuf-config.cmake安装时创建的脚本。因此,该函数只能与已安装的 Protobuf 一起使用,而不能与 FetchContent 中包含的 Protobuf 一起使用。

在主控中(之后那个拉取请求) 功能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(...)


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 FetchContent 安装 protobuf 时如何使用 cmake 命令 protobuf_generate? 的相关文章

随机推荐