简体   繁体   English

是否可以使用 cmake 的 FetchContent 包含 protobuf?

[英]Is it possible to include protobuf using cmake's FetchContent?

I want to use protobuf in my C++ library.我想在我的 C++ 库中使用protobuf All dependencies so far are included using cmake's FetchContent module.到目前为止,所有依赖项都是使用 cmake 的FetchContent模块包含的。 I want to do the same with protobuf .我想对protobuf做同样的事情。 However, I run into the following problem: Unknown CMake command "protobuf_generate_cpp".但是,我遇到了以下问题: Unknown CMake command "protobuf_generate_cpp". Any hints on how to solve this?关于如何解决这个问题的任何提示?

Excerpt of my CMakeLists.txt :我的CMakeLists.txt摘录:

FetchContent_Declare(fmt
        GIT_REPOSITORY https://github.com/fmtlib/fmt.git
        GIT_TAG 9.0.0)

FetchContent_Declare(protobuf
        GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
        GIT_TAG v21.4)

FetchContent_MakeAvailable(fmt protobuf)

include_directories(${Protobuf_INCLUDE_DIRS})
include_directories(${CMAKE_CURRENT_BINARY_DIR})

protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS message.proto)

This works for me:这对我有用:

FetchContent_Declare(protobuf
  GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
  GIT_TAG        v21.4
  SOURCE_SUBDIR  cmake
  FIND_PACKAGE_ARGS NAMES protobuf
)
FetchContent_MakeAvailable(protobuf)

On the consumer end do this在消费者端这样做

include(FindProtobuf)
find_package(protobuf CONFIG REQUIRED)

Note: This has only been tested on CMake v3.25注意:这仅在 CMake v3.25 上测试过

protobuf_generate_cpp is from FindProtobuf . protobuf_generate_cpp来自FindProtobuf It doesn't seem to work with a protoc that was build in the project with FetchContent .它似乎不适用于在项目中使用protoc构建的FetchContent You'll have to call the protoc binary explicitly.您必须显式调用protoc二进制文件。

set(GENERATED_CODE_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated)
set(PROTO_SRCS ${GENERATED_CODE_DIR}/message.pb.cc)
set(PROTO_HDRS ${GENERATED_CODE_DIR}/message.pb.h)
set(PROTOC ${protobuf_BINARY_DIR}/protoc)
set(PROTO_DIR ${CMAKE_CURRENT_SOURCE_DIR})

add_custom_command(
    OUTPUT ${PROTO_SRCS} ${PROTO_HDRS}
    COMMAND ${PROTOC} --proto_path ${PROTO_DIR} message.proto --cpp_out ${GENERATED_CODE_DIR}
    DEPENDS ${PROTOC} ${PROTO_DIR}/message.proto
    )

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

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