gRPCのC++版のメモ。
|
gRPCを使ったC++アプリケーションをビルドするには、ヘッダーファイルをインストールしておく必要がある。
gRPCをLinuxへインストールするには、GitHubのgrpcをクローンしてソースからビルドする。
以下の例では、「$HOME/.local」の下の「include」にヘッダーファイルがインストールされる。
git clone --recurse-submodules -b v1.67.1 --depth 1 --shallow-submodules https://github.com/grpc/grpc cd grpc mkdir -p cmake/build cd cmake/build cmake -DgRPC_INSTALL=ON -DgRPC_BUILD_TESTS=OFF -DCMAKE_INSTALL_PREFIX=$HOME/.local ../.. make -j 4 make instal
gRPCをWindowsへインストールするには、vcpkgというインストーラーを使用するので、まずvcpkgをインストールする必要がある。
コマンドプロンプトから以下のコマンドを実行する。
(ソースからのビルドになるので、完了するまでけっこう時間がかかる)
git clone https://github.com/microsoft/vcpkg.git cd vcpkg bootstrap-vcpkg.bat dir vcpkg.exe
vcpkg install grpc dir installed\x64-windows\include\
C++で書かれたgRPCアプリケーション(サーバー・クライアント)をビルドするには、CMakeとmakeを使う。
cmake_minimum_required(VERSION 3.8)
project(ExampleGrpc C CXX)
find_package(Threads REQUIRED)
option(protobuf_MODULE_COMPATIBLE TRUE)
find_package(Protobuf CONFIG REQUIRED)
message(STATUS "Using protobuf ${Protobuf_VERSION}")
set(_PROTOBUF_LIBPROTOBUF protobuf::libprotobuf)
set(_REFLECTION gRPC::grpc++_reflection)
set(_PROTOBUF_PROTOC $)
find_package(gRPC CONFIG REQUIRED)
message(STATUS "Using gRPC ${gRPC_VERSION}")
set(_GRPC_GRPCPP gRPC::grpc++)
set(_GRPC_CPP_PLUGIN_EXECUTABLE $)
# Proto file
get_filename_component(proto_file "../proto/example.proto" ABSOLUTE)
get_filename_component(proto_path "${proto_file}" PATH)
# Generated sources
set(proto_srcs "${CMAKE_CURRENT_BINARY_DIR}/example.pb.cc")
set(proto_hdrs "${CMAKE_CURRENT_BINARY_DIR}/example.pb.h")
set(grpc_srcs "${CMAKE_CURRENT_BINARY_DIR}/example.grpc.pb.cc")
set(grpc_hdrs "${CMAKE_CURRENT_BINARY_DIR}/example.grpc.pb.h")
add_custom_command(
OUTPUT "${proto_srcs}" "${proto_hdrs}" "${grpc_srcs}" "${grpc_hdrs}"
COMMAND ${_PROTOBUF_PROTOC}
ARGS --grpc_out "${CMAKE_CURRENT_BINARY_DIR}"
--cpp_out "${CMAKE_CURRENT_BINARY_DIR}"
-I "${proto_path}"
--plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}"
"${proto_file}"
DEPENDS "${proto_file}")
# Include generated *.pb.h files
include_directories("${CMAKE_CURRENT_BINARY_DIR}")
# grpc_proto
add_library(grpc_proto
${grpc_srcs}
${grpc_hdrs}
${proto_srcs}
${proto_hdrs})
target_link_libraries(grpc_proto
${_REFLECTION}
${_GRPC_GRPCPP}
${_PROTOBUF_LIBPROTOBUF})
# Targets
foreach(_target
ExampleService Int64PairClient
)
add_executable(${_target} "${_target}.cpp")
target_link_libraries(${_target}
grpc_proto
${_REFLECTION}
${_GRPC_GRPCPP}
${_PROTOBUF_LIBPROTOBUF})
endforeach()
srcのひとつ上のディレクトリーから以下のコマンドを実行してビルドすると、実行ファイルが作られる。
mkdir -p cmake/build cd cmake/build/ cmake -DCMAKE_INSTALL_PREFIX=$HOME/.local ../../src make -j 4
CMAKE_INSTALL_PREFIXには、gRPCのヘッダーファイルをインストールした場所を指定する。
その後ろの引数(上の例では「../../src」)には、CMakeLists.txtがある場所を指定する。
makeを実行すると、カレントディレクトリー(すなわちcmake/buildの直下)に実行ファイルが生成される。