You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

gRPC项目编译报错:undefined reference to `grpc::ServerBuilder::AddListeningPort`求助

gRPC编译链接错误解决指南

核心问题定位

从错误信息(链接阶段出现undefined reference类错误,指向gRPC/Protobuf相关函数)和CMake配置来看,问题出在gRPC与Protobuf库未正确引入或链接。

修正CMakeLists.txt的关键步骤

1. 正确查找依赖包

在CMakeLists.txt开头添加依赖查找逻辑:

# 若为源码编译的gRPC,需先指定安装路径的cmake目录
# set(gRPC_DIR "/usr/local/lib/cmake/grpc" CACHE PATH "Path to gRPC cmake config")

find_package(gRPC REQUIRED)
find_package(Protobuf REQUIRED)

2. 完整链接必要库

编译服务端和客户端时,必须链接gRPC的C++库、反射库(服务端可选但建议添加)以及Protobuf库:

# 假设你的源文件为server.cpp、client.cpp,proto生成的文件为helloworld.grpc.pb.cc、helloworld.pb.cc
add_executable(server server.cpp helloworld.grpc.pb.cc helloworld.pb.cc)
target_link_libraries(server
    gRPC::grpc++
    gRPC::grpc++_reflection
    ${PROTOBUF_LIBRARIES}
)

add_executable(client client.cpp helloworld.grpc.pb.cc helloworld.pb.cc)
target_link_libraries(client
    gRPC::grpc++
    ${PROTOBUF_LIBRARIES}
)

3. 自动生成Proto代码(推荐)

避免手动生成代码出错,用CMake内置的Protobuf模块自动生成:

protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS helloworld.proto)
protobuf_generate_grpc_cpp(GRPC_SRCS GRPC_HDRS helloworld.proto)

# 用自动生成的源文件编译
add_executable(server server.cpp ${PROTO_SRCS} ${GRPC_SRCS})
target_link_libraries(server gRPC::grpc++ gRPC::grpc++_reflection ${PROTOBUF_LIBRARIES})

额外排查项

  • 确认gRPC与Protobuf版本匹配(版本不匹配会导致符号不兼容)
  • 检查本地安装的gRPC是源码编译还是系统包安装,确保CMake能找到正确的配置文件
  • 编译架构需一致(如x86_64程序不能链接arm架构的gRPC库)

内容的提问来源于stack exchange,提问作者Jasonhua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 18:12:13