首页 > 代码库 > Windows上编译GRPC

Windows上编译GRPC

Windows上源码编译多数开源软件都很麻烦

 

编译环境:VS2015(grpc支持2013及以上,2012上没有Nuget,编译起来要费劲的多)

编译GRPC涉及内容

  • grpc
  • protobuf
  • grpc_protoc_plugin(本文以c++语言为编译目标,因此只涉及grpc_cpp_plugin)
  • zlib

 

grpc代码下载后,执行git submodule update --init初始化依赖的submodule

1. protobuf

参考readme用CMAKE生成工程文件,编译即可

2. grpc,grpc_protoc_plugin:在vsprojects里有建好的工程文件,用vs2015编译基本不会遇到什么问题,除了:

    grpc_cpp_plugin依赖libprotoc.lib,而protobuf生成的库名称为libprotocd.lib,这块需要手动改一下

3. zlib 参考readme

 

上面的几步都是很顺利的,grpc和protobuf默认都是静态库编译,不会遇到链接错误,下面尝试编译example/cpp/helloworld

1. 修改CmakeFiles.txt,由于helloworld依赖protobuf需要在命令行指定protobuf的protobuf-config.cmake所在位置

cmake -Dprotobuf_DIR=

grpc我是使用自带的工程文件编译的,没找到对应的config.cmake,我是把对grpc的依赖去掉了,改成:

# Minimum CMake requiredcmake_minimum_required(VERSION 2.8)# Projectproject(HelloWorld CXX)# Protobufset(protobuf_MODULE_COMPATIBLE TRUE)find_package(protobuf CONFIG REQUIRED)message(STATUS "Using protobuf ${protobuf_VERSION}")# gRPC#find_package(gRPC CONFIG)message(STATUS "Using gRPC ${gRPC_VERSION}")# grpc相关的目录配置include_directories("C:/path/to/grpc/include")link_directories("C:/path/to/grpc/vsprojects/Debug")link_directories("C:/path/to/grpc/third_party/zlib")link_directories("C:/path/to/grpc/vsprojects/packages/grpc.dependencies.openssl.1.0.204.1/build/native/lib/v140/Win32/Debug/static")add_definitions(-D_WIN32_WINNT=0x0601)set(gRPC_CPP_PLUGIN_EXECUTABLE "C:/path/to/grpc/vsprojects/Debug/grpc_cpp_plugin.exe")# Proto fileget_filename_component(hw_proto "../../protos/helloworld.proto" ABSOLUTE)get_filename_component(hw_proto_path "${hw_proto}" PATH)# Generated sourcesprotobuf_generate_cpp(hw_proto_srcs hw_proto_hdrs "${hw_proto}")set(hw_grpc_srcs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.cc")set(hw_grpc_hdrs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.h")add_custom_command(      OUTPUT "${hw_grpc_srcs}" "${hw_grpc_hdrs}"      COMMAND protobuf::protoc      ARGS --grpc_out "${CMAKE_CURRENT_BINARY_DIR}" -I "${hw_proto_path}"        --plugin=protoc-gen-grpc="${gRPC_CPP_PLUGIN_EXECUTABLE}"        "${hw_proto}"      DEPENDS "${hw_proto}")# Generated include directoryinclude_directories("${CMAKE_CURRENT_BINARY_DIR}")# Targets greeter_[async_](client|server)foreach(_target  greeter_client greeter_server  greeter_async_client greeter_async_server)  add_executable(${_target} "${_target}.cc"    ${hw_proto_srcs}    ${hw_grpc_srcs})# 添加对应的lib库依赖  target_link_libraries(${_target}    protobuf::libprotobuf    grpc++_unsecure    grpc++    grpc++_reflection    zlib    grpc    gpr    ws2_32    grpc_unsecure    libeay32    ssleay32    libvcruntimed)endforeach()

 

2. 生成出工程文件后,需要修改greeter_client/server的CRT依赖为/MTd(因为上面的grpc等默认都是/MTd)

3. 编译即可

4. 这时应该会遇到找不到Grpc内的某个符号,比如Channel、Complete_quque等, 以下以channel为例说明解决方法:

    GRPC编译grpc++.lib时,生成的Channel.obj会被覆盖(原因没查出来,大概是因为grpc.lib编译时同样会生成channel.obj)

    删掉obj目录中C:\path\to\grpc\vsprojects\IntDir\grpc++中的channel.obj,然后在工程里“生成”(不要重新生成)

5. 解决了上面的问题,应该就可以生成可执行文件了

 

Windows上编译GRPC