近期需要使用grpc在目标主机使用,参考了官方示例,大部分网上教程完成了本篇grpc的交叉编译,并对参考的教程做出了引用
交叉编译grpc
实验环境:
docker ubuntu16.04
cmake version 3.16.1
gcc version 7.5.0
set(PACKAGE_NAME “grpc”)
set(PACKAGE_VERSION “1.28.2”)
set(gRPC_CORE_VERSION “9.0.0”)
- 目标:C++中能够使用 grpc(静态/动态链接库皆可,本文根据官方cmake的编译示例,最后生成的是静态)
!!! Note 如果使用的是make或者参考的非官方的方法,可见其他注意事项,强烈建议根据官方方法,虽然可能可能也会遇到许多问题(官方以及非官方方法本人最终都在该环境下编译成功)
1 安装交叉编译库
添加进环境变量
sudo vim .zshrc/.bashrc
export PATH="$PATH:/cross-compile_toolchain/toolchain/bin"
export STAGING_DIR="/cross-compile_toolchain/toolchain/bin:$STAGING_DIR"
❯ source ~/.zshrc/.bashrc
❯ arm-linux-gcc -v
2 Pre-requisites
安装必要的依赖工具,这里使用cmake进行编译
❯ sudo apt-get install build-essential autoconf libtool pkg-config
❯ sudo apt-get install cmake automake
ubuntu16.04自带的cmake和gcc版本可能会在build中发生意想不到的错误!
同时查看源码中的CMakeLists.txt可以发现
cmake_minimum_required(VERSION 3.5.1)
# We can install dependencies from submodules if we're running
# CMake v3.13 or newer.
if(CMAKE_VERSION VERSION_LESS 3.13)
set(_gRPC_INSTALL_SUPPORTED_FROM_MODULE OFF)
else()
set(_gRPC_INSTALL_SUPPORTED_FROM_MODULE ON)
endif()
目前还不知道该版本编译是否有gcc cmake具体的版本要求。
2.1 ubuntu16.04升级gcc/g++/cmake
# Install CMake 3.16
❯ apt-get update && apt-get install -y wget
❯ wget -q -O cmake-linux.sh https://github.com/Kitware/CMake/releases/download/v3.16.1/cmake-3.16.1-Linux-x86_64.sh
❯ sh cmake-linux.sh -- --skip-license --prefix=/usr
❯ rm cmake-linux.sh
❯ ❯ cmake -v
# update gcc/g++
❯ sudo apt-get install -y software-properties-common
❯ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
❯ sudo apt update
❯ sudo apt install g++-7 -y
❯ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-7 60 \
--slave /usr/bin/g++ g++ /usr/bin/g++-7
❯ sudo update-alternatives --config gcc
❯ gcc -v
❯ g++ -v
3 安装源代码
这里选用 v1.28.2
❯ git clone https://github.com/grpc/grpc.git docker-grpc
❯ cd docker-grp
# 切换到指定版本
❯ git checkout v1.28.2
# 下载第三方依赖库
❯ git submodule update --init
git submodule update --init失败可查看
4 构建(使用CMake)
You can use CMake to cross-compile gRPC for another architecture. In order to do so, you will first need to build protoc and grpc_cpp_plugin for the host architecture. These tools are used during the build of gRPC, so we need copies of executables that can be run natively.
☝出自官方参考教程Cross-compiling中,可以看到grpc交叉编译时的一些注意事项:
- gRPC交叉编译之前,需要先交叉编译好protobuf
- gRPC需要先生成宿主机平台的protobuf和gRPC
- 原因是在gRPC交叉编译的过程中,需要使用对应的编译平台的bin文件(protoc,grpc_cpp_plugin等等)

本文详细介绍了如何在Ubuntu 16.04环境下使用CMake完成grpc的交叉编译过程,包括安装交叉编译库、预置环境、安装源代码、构建及测试等步骤,并针对可能出现的问题提供了相应的解决方案。
最低0.47元/天 解锁文章
4489





