簡體   English   中英

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

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

我想在我的 C++ 庫中使用protobuf 到目前為止,所有依賴項都是使用 cmake 的FetchContent模塊包含的。 我想對protobuf做同樣的事情。 但是,我遇到了以下問題: Unknown CMake command "protobuf_generate_cpp". 關於如何解決這個問題的任何提示?

我的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)

這對我有用:

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)

在消費者端這樣做

include(FindProtobuf)
find_package(protobuf CONFIG REQUIRED)

注意:這僅在 CMake v3.25 上測試過

protobuf_generate_cpp來自FindProtobuf 它似乎不適用於在項目中使用protoc構建的FetchContent 您必須顯式調用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