使用 docker 创建 NDK 开发环境

  • 编写 Dockerfile

    FROM ubuntu:18.04
    
    RUN sed -i 's/http:\/\/archive\.ubuntu\.com\/ubuntu\//http:\/\/mirrors\.163\.com\/ubuntu\//g' /etc/apt/sources.list
    RUN apt-get -y update
    RUN apt-get install -y make wget cmake git autoconf automake libtool file
    RUN DEBIAN_FRONTEND=noninteractive apt-get install -y tzdata
    RUN mkdir /build && \
        cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
        echo "Asia/Shanghai" > /etc/timezone
    RUN apt-get install -y android-tools-adb
    RUN apt-get install -y unzip
    RUN echo no | dpkg-reconfigure dash
    RUN wget -c https://dl.google.com/android/repository/android-ndk-r17-beta2-linux-x86_64.zip?hl=zh-cn -O /build/android-ndk-r17-beta2-linux-x86_64.zip
    RUN unzip /build/android-ndk-r17-beta2-linux-x86_64.zip -d /opt/
    RUN rm /build/android-ndk-r17-beta2-linux-x86_64.zip
    RUN apt-get install -y python
    RUN /opt/android-ndk-r17-beta2/build/tools/make_standalone_toolchain.py --arch arm64 --api 24 --stl=libc++ --install-dir /opt/android-toolchain
    RUN echo $'export PATH=/opt/android-toolchain/bin:$PATH\n\
    export CC=aarch64-linux-android-clang\n\
    export CXX=aarch64-linux-android-clang++\n\
    export LD=aarch64-linux-android-ld\n\
    export AR=aarch64-linux-android-ar\n\
    export STRIP=aarch64-linux-android-strip\n\
    export RANLIB=aarch64-linux-android-ranlib\n\
    export AS=aarch64-linux-android-clang\n\
    export CFLAGS="-fPIE"\n\
    export CXXFLAGS="$CFLAGS"\n\
    export LDFLAGS="-fPIE -pie"\n\
    export SYSROOT=/opt/android-toolchain/sysroot\n\
    export CROSS_COMPILE_HOST=aarch64-linux-android' > /root/.ndkrc
    
    WORKDIR /build
    
    ENTRYPOINT ["/bin/bash"]
    
  • 构建 docker 镜像

    docker build -f Dockerfile --network=host -t ndk:r17-beta2 .
    
  • 运行 docker 容器

    docker run --rm --network=host -v ${HOME}/.android:/root/.android -it ndk:r17-beta2
    

    下面的命令全部在 docker 容器中执行。

  • 交叉编译程序

    cat > hello.c <<EOF
    #include <stdio.h>
    int main() {
        printf("hello ndk\n");
        return 0;
    }
    EOF
    . ~/.ndkrc
    $CC $CFLAGS $LDFLAGS hello.c -o hello
    
  • 在设备上运行程序

    假设设备 IP 为 192.168.1.3

    adb connect 192.168.1.3
    adb root
    adb connect 192.168.1.3
    adb remount
    adb connect 192.168.1.3
    adb push ./hello /tmp/hello
    adb shell /tmp/hello
    

    最终将输出结果 hello ndk