QT qmake GRPC实现

Met*_*ucu 8 c++ qt qmake grpc

我想在我的 qt 项目上实现 GRPC,但首先我尝试运行 grpc 示例,但出现未定义的引用错误。

主要.cpp:

#include <helloworld.grpc.pb.h>

#include <grpc/grpc.h>
#include <grpcpp/server_builder.h>

#include <iostream>

class GreeterService final : public helloworld::Greeter::Service {
public:
  virtual ::grpc::Status SayHello(::grpc::ServerContext* context, const ::helloworld::HelloRequest* request, ::helloworld::HelloReply* response) {
    std::cout << "Server: message for \"" << request->name() << "\"." << std::endl;

    response->set_message("Hi " + request->name());

    return grpc::Status::OK;
  }
};

int main(int argc, char* argv[]) {
  grpc::ServerBuilder builder;
  builder.AddListeningPort("0.0.0.0:50051", grpc::InsecureServerCredentials());

  GreeterService my_service;
  builder.RegisterService(&my_service);

  std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
  server->Wait();

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

。轮廓:

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++17

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \

INCLUDEPATH += /home/grpc/include \
               /home/grpc/
DEPENDPATH  += /home/grpc//include \
               /home/grpc/
QMAKE_LFLAGS += -Wl,-rpath,"path_to_libgrpc++.so.1.45"
LIBS += -L/usr/local/lib `pkg-config --libs protobuf grpc++` -L/usr/lib -L/usr/lib64 -L/usr/lib/x86_64-linux-gnu


# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
Run Code Online (Sandbox Code Playgroud)

错误:

undefined reference to `helloworld::Greeter::Service::Service()'
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会出现此错误,编译器可以看到 headers main 也可以看到。但我认为我的 .pro 文件中缺少一些内容

小智 2

您看到的错误可能是由于您没有正确链接到 gRPC 库。

要解决此问题,您需要确保链接到项目文件 (.pro) 中的 gRPC 库。您可以通过将以下行添加到 .pro 文件中来完成此操作:

LIBS += -lgrpc++
Run Code Online (Sandbox Code Playgroud)

这将告诉链接器链接到 gRPC C++ 库,其中包括您尝试使用的 helloworld::Greeter::Service 类。

如果库不在标准库搜索路径中,您可能还需要指定该库的路径。您可以通过将以下行添加到 .pro 文件中来完成此操作:

LIBS += -L/path/to/libgrpc++.so
Run Code Online (Sandbox Code Playgroud)

将 /path/to/libgrpc++.so 替换为系统上 libgrpc++.so 库的实际路径。

将这些行添加到 .pro 文件后,请尝试重建项目。这应该可以解决未定义的引用错误。