本文章参与<零声教育>的C/C++Linux服务器高级架构系统教程学习:
1 安装必要的依赖工具
安装必要的依赖工具
sudo apt-get install autoconf automake libtool
如果cmake低于3.15, gcc/g++ 低于 7.0 ,请根据文档进行安装。查看版本的方式
# 检查cmake版本
cmake -version
# 检查gcc/g++版本
gcc -v
g++ -v
1.1 安装 cmake
1. 卸载已经安装的旧版的CMake
sudo apt-get autoremove cmake
2. 文件下载解压
wget https://cmake.org/files/v3.23/cmake-3.23.0-linux-x86_64.tar.gz
tar zxf cmake-3.23.0-linux-x86_64.tar.gz
3. 创建软链接
注: 文件路径是可以指定的, 一般选择在/opt
或 /usr
路径下, 这里选择/opt
sudo mv cmake-3.23.0-linux-x86_64 /opt/cmake-3.23.0
sudo ln -sf /opt/cmake-3.23.0/bin/* /usr/bin/
4. 测试版本
ubuntu@VM-16-11-ubuntu:~/rpc$ cmake -version
cmake version 3.23.0
CMake suite maintained and supported by Kitware (kitware.com/cmake).
1.2 安装gcc/gdb
升级gcc和gdb的版本,至少需要6.3以上的版本。
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
2 编译grpc
下载源码
git clone https://github.com/grpc/grpc
查看版本并选择合适的版本,这里选择v1.45.2相对较新的版本
git tag
git checkout v1.45.2
查看此时grpc目录内容的大小du -h --max-depth=1, 可以看到427M左右
ubuntu@VM-16-11-ubuntu:~/rpc/grpc$ du -h --max-depth=1
348M ./.git
32K ./summerofcode
1.5M ./doc
6.5M ./tools
4.0K ./spm-core-include
24M ./test
80K ./cmake
3.0M ./third_party
4.0K ./spm-cpp-include
1.5M ./templates
8.0K ./.bazelci
1.9M ./include
5.0M ./examples
34M ./src
268K ./etc
64K ./.github
284K ./bazel
427M .
下载第三方依赖库,下载完后会发现整个grpc目录内容明显变大=
git submodule update --init
再次查看 目录大小,占用了1.3G。
ubuntu@VM-16-11-ubuntu:~/rpc/grpc$ du -h --max-depth=1
899M ./.git
32K ./summerofcode
1.5M ./doc
6.5M ./tools
4.0K ./spm-core-include
24M ./test
80K ./cmake
291M ./third_party
4.0K ./spm-cpp-include
1.5M ./templates
8.0K ./.bazelci
1.9M ./include
5.0M ./examples
34M ./src
268K ./etc
64K ./.github
284K ./bazel
1.3G
编译和安装
mkdir -p cmake/build
cd cmake/build
cmake ../..
make
sudo make install
3 protobuf安装
不用手动安装protobuf,不然版本可能和grcp不匹配,必须在 grpc 执行 git submodule update --init 命令之后生成的 third_party/protobuf 里面编译安装对应的 protobuf。
cd third_party/protobuf/
./autogen.sh
./configure --prefix=/usr/local
make
sudo make install
sudo ldconfig # 使得新安装的动态库能被加载
protoc --version
显示3.19.4
4 测试环境
编译helloworld
cd grpc/examples/cpp/helloworld/
mkdir build
cd build/
cmake ..
make登录后复制
启动服务和客户端
# 启动服务端,监听在50051端口
./greeter_server
Server listening on 0.0.0.0:50051
# 启动客户端,服务端返回Hello world
./greeter_client
Greeter received: Hello world
5 参考
ubuntu搭建grpc for C++开发环境wx5bb365de633ed的技术博客51CTO博客 该文档提供修改grpc第三方库下载地址的方式进行安装。