首页 > 解决方案 > CMake 括号#include grpc

问题描述

我试图通过尝试将代码集成到 grpc 示例 helloworld 目录中来将 grpc 与大型项目集成:greeter_client.cc

我使用了 cmake 选项,假设 grpc 已经安装在我的系统中的 $MY_INSTALL_DIR 中,如 grpc 的文档中所述:cmake -DCMAKE_PREFIX_PATH=$MY_INSTALL_DIR

当我将它包含在我的“大型项目”中时,我将 greeter_client.cc 更改为 .h 和 .cc 文件。

greeter_client.h

#include <grpcpp/grpcpp.h>

#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif

using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;

class GreeterClient {
 public:
  GreeterClient(std::shared_ptr<Channel> channel)
      : stub_(Greeter::NewStub(channel)) {}

  std::string SayHello(const std::string& user);

 private:
  std::unique_ptr<Greeter::Stub> stub_;
};

void libFun();

greeter_client.cc

#include <iostream>
#include <memory>
#include <string>

#include "greeter_client.h"

  std::string GreeterClient::SayHello(const std::string& user) {
     // the original implementation unchanged...
  }

void libFun() {
  GreeterClient client(grpc::CreateChannel(
      "localhost:50051", grpc::InsecureChannelCredentials()));
  client.SayHello("world");
}

在目标目的地(比如文件是 main.cc)我添加了

    #include "/path/to/greeter_cient.h"
    int main (){
      libFun();
      return 0;
    }

目录结构是

main.cc 的 CMakeList 如下所示

    cmake_minimum_required(VERSION 3.5.1)

    project(test C CXX)


  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")


  # This part is copied from the grpc example CMakeFileList
  set(protobuf_MODULE_COMPATIBLE TRUE)
  find_package(Protobuf CONFIG REQUIRED)
  message(STATUS "Using protobuf ${Protobuf_VERSION}")

  set(_PROTOBUF_LIBPROTOBUF protobuf::libprotobuf)

  # Find gRPC installation
  # Looks for gRPCConfig.cmake file installed by gRPC's cmake installation.
  find_package(gRPC CONFIG REQUIRED)
  message(STATUS "Using gRPC ${gRPC_VERSION}")

  set(_GRPC_GRPCPP gRPC::grpc++)

add_subdirectory("../helloworld" "../helloworld")

add_executable(program "main.cc")
# THIS IS THE QUESTION: why adding ${_GRPC_GRPCPP} will work?
target_link_libraries(program greeter_client 
    ${_GRPC_GRPCPP})
target_include_directories(program PRIVATE "../helloworld" )

问题是:最初,我没有在 main.cc 的 CMakeList 中添加 find_project(gRPC) ,也没有在程序目标的 target_link_libraries 中添加 ${_GRPC_GRPCPP} 。我会收到错误抱怨“/test/../helloworld/greeter_client.h:23:10: fatal error: 'grpcpp/grpcpp.h' file not found #include <grpcpp/grpcpp.h>”

我阅读了一些线程,似乎括号包含在系统包含路径中找到了文件。我不确定为什么 grpc 示例可以通过在 target_link_libraries 中添加依赖项来使其工作?

另一个问题是:理想情况下,我希望 main.cc 不关心 greeter_client 目标中的任何内容。但是,由于我必须包含 greeter_client.h ,而后者又包含 <grpcpp/grpcpp.h> 我必须添加 find_project 并将目标链接到 main.cc 的 CMakeList 中。如何避免在 main.cc 的 CMakeList 中重新处理这个 include <grpcpp/grpcpp.h>?

谢谢!

标签: c++cmakeincludegrpc

解决方案


如果我理解正确,这里真正的问题是

似乎括号包含在系统包含路径中找到文件。我不确定为什么 grpc 示例可以通过添加依赖项来使其工作target_link_libraries

简而言之,#include <foo.h>搜索系统是否会首先包含路径,但如果失败,它将像您写的一样重试#include "foo.h"


推荐阅读