首页 > 解决方案 > 在 CMAKE 中为库目标生成 grpc 文件

问题描述

在以下项目结构中(来自我之前的问题):

root/
├─ CMakeLists.txt
├─ protocol/
│  ├─ msg.proto
│  ├─ myrpc.proto
│  ├─ CMakeLists.txt
├─ app/
│  ├─ main.cpp
│  ├─ CMakeLists.txt

我可以生成 protobuf 文件并将它们作为依赖项添加到app目标中。现在我正在尝试在同一个库中生成 grpc 文件。

基于此答案博客文章的 grpc 生成功能有问题;因为打印了以下错误消息:

-- Configuring done
-- Generating done
-- Build files have been written to: /media/davids91/Work/rafko/src/main/cxx/build
[  1%] Running grpc protocol buffer compiler on /usr/local/bin/grpc_cpp_plugin
/usr/local/bin/grpc_cpp_plugin: File does not reside within any path specified using --proto_path (or -I).  You must specify a --proto_path which encompasses this file.  Note that the proto_path must be an exact prefix of the .proto file names -- protoc is too dumb to figure out when two paths (e.g. absolute and relative) are equivalent (it's harder than you think).
make[2]: * [protocol/CMakeFiles/protocol.dir/build.make:138: /media/usr/local/bin/grpc_cpp_plugin.grpc.pb.h] Error 1
make[1]: * [CMakeFiles/Makefile2:276: protocol/CMakeFiles/protocol.dir/all] Error 2
make: * [Makefile:103: all] Error 2

我可以看到安装文件夹看起来是正确的,因为这是从源代码安装 grpc 库的位置。

根 CMakeLists.txt:

cmake_minimum_required(VERSION 3.18.4) 
project(
  root
  VERSION 0.1
  LANGUAGES CXX
)

add_subdirectory(protocol)
add_subdirectory(app) 

协议 CMakeLists.txt:

add_library(protocol)
target_include_directories(protocol
  PUBLIC
  .
  ${CMAKE_CURRENT_BINARY_DIR}
  ${Protobuf_INCLUDE_DIRS}
)
find_package(Protobuf REQUIRED)
find_package(gRPC CONFIG REQUIRED)
target_link_libraries(protocol ${Protobuf_LIBRARIES})
get_target_property(grpc_cpp_plugin_location gRPC::grpc_cpp_plugin LOCATION)

protobuf_generate( TARGET protocol LANGUAGE CPP PROTOS msg.proto )
protobuf_generate( 
    TARGET
        protocol 
    LANGUAGE
        grpc 
    PROTOS 
        myrpc.proto 
    PLUGIN
        "protoc-gen-grpc=${grpc_cpp_plugin_location}"
)

应用 CMakeLists.txt:

add_library(app)
target_link_libraries(app PUBLIC protocol)
target_include_directories(app PUBLIC .)
target_sources(app
  PRIVATE
  main.cpp
)

这个解决方案可能缺少什么来生成基于插件的 grpc 文件?

标签: c++cmakegrpc

解决方案


经过一些实验并仔细查看了这里的示例,我想通了!

我更新了协议 CMakeLists.txt: changed

find_package(Protobuf REQUIRED)

find_package(Protobuf CONFIG REQUIRED)

我认为它告诉 CMake proto 文件正在配置时处理,但欢迎任何更深入的解释!


推荐阅读