ubuntu20.04编译适用于16.04的程序

前面遇到过,ubuntu20.04上编的程序,在16.04上运行会报错,因为GLIBC版本不兼容。那么除了找一台ubuntu 16.04的编译机,其实更简单的办法是在本机(ubuntu20.04)上开启一个16.04的容器,把代码目录挂载进去,在容器里面进行编译。

首先基于官方16.04的镜像,构建一个带编译环境的镜像。参考Dockerfile,

# Use the following cmd to build.
# docker build -t=test:v1 .
 
FROM registry.example.com/base/ubuntu:16.04
RUN apt-get update ; \
    apt-get install -y g++-4.8 make
RUN rm -rf /var/lib/apt/lists/*
RUN echo "hello hbb from dockerfile" > /root/hello.txt
 
 
CMD ["/bin/bash"]

建设编好之后的镜像如下,

$ docker images
REPOSITORY                         TAG         IMAGE ID       CREATED         SIZE
compile-cmake                      16.04       507ec822f6da   2 days ago      445MB
compile                            16.04       2e8e4df80524   11 months ago   402MB

可以用如下脚本,方便地切换到16.04的环境编译,

#!/bin/bash
 
target=$1
if [ -z "$target" ]; then
    target=feeder_handler
fi
docker run --rm \
    -v /home/yychi/code/mdl_src:/home/yychi/code/mdl_src \
    -v /mdl/dependency/:/mdl/dependency \
    2e8e4df80524  bash -c \
    "cd /home/yychi/code/mdl_src/build/make && make -j3 $target"

这样一来,每次运行脚本,会基于compile:16.04创建一个容器,然后执行编译,执行结束后容器销毁,干净利落。