在这篇文章中,我记录了如何在Termux上使用Arch Linux运行NDK,重点是通过脚本测试C和C++编译器的执行,确保成功生成并验证了适用于ARM架构的二进制文件
前言
上篇文章讲了如何在termux
上快速安装arch linux
,然后就可以玩一些好玩的,Google发行的NDK并不支持ARM架构
下载NDK
在Android开发者网站上下载NDK,下载地址为:https://developer.android.com/ndk/downloads
然后解压到root目录下
1
unzip android-ndk-r27b-linux.zip
然后安装zip
工具链并新建一个test目录
1
2
pacman -S zip &&
mkdir test && cd test && touch test.sh
并填入以下内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/bin/sh
set -eu
TEST_DIR = " $( dirname " $( realpath " $0 " ) " ) "
## ndk clang resource dir, get by command: <ndk_root>/toolchains/llvm/prebuilt/linux-x86_64/bin/clang --print-resource-dir
RESOURCE_DIR = " ${ TEST_DIR } /../android-ndk-r27b/toolchains/llvm/prebuilt/linux-x86_64/lib/clang/18/"
## ndk sysroot, typically <ndk_root>/toolchains/llvm/prebuilt/linux-x86_64/sysroot/
SYSROOT = " ${ TEST_DIR } /../android-ndk-r27b/toolchains/llvm/prebuilt/linux-x86_64/sysroot/"
## Android target triple
TARGET = aarch64-linux-android21
if command -v clang; then
CLANG = clang
elif command -v zig; then
CLANG = "zig cc"
else
print "Cannot find clang or zig\n" >& 2
exit 1
fi
## These options are needed for llvmbox
# -isystem "${SYSROOT}/usr/include/c++/v1" \
# -isystem "${SYSROOT}/usr/include" \
# -isystem "${SYSROOT}/usr/include/aarch64-linux-android"
mkdir -p " ${ TEST_DIR } /output"
echo "Test C compiler..."
${ CLANG } \
-B " ${ TEST_DIR } /bin" \
-resource-dir " ${ RESOURCE_DIR } " \
--sysroot= " ${ SYSROOT } " \
--target= " ${ TARGET } " \
-xc - \
" $@ " \
-o " ${ TEST_DIR } /output/hello-c" \
<<-EOF
#include <stdio.h>
int main() {
printf("%s\n", "Hello, C!");
return 0;
}
EOF
echo "Test C++ compiler..."
${ CLANG } \
-B " ${ TEST_DIR } /bin" \
-resource-dir " ${ RESOURCE_DIR } " \
--sysroot= " ${ SYSROOT } " \
--target= " ${ TARGET } " \
-xc++ -lc++ - \
" $@ " \
-o " ${ TEST_DIR } /output/hello-cpp" \
<<-EOF
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!\n";
return 0;
}
EOF
if command -v file >/dev/null; then
file " ${ TEST_DIR } /output/hello-c" " ${ TEST_DIR } /output/hello-cpp"
fi
测试
在test
目录下执行sh test.sh
,会打印出以下日志
1
2
3
4
5
6
/bin/clang
Test C compiler...
Test C++ compiler...
/root/test//output/hello-c:
ELF 64-bit LSB pie executable, ARM aarch64, version 1 ( SYSV) , dynamically linked, interpreter /system/bin/linker64, BuildID[ xxHash]= 10df539d438a8009, not stripped
/root/test//output/hello-cpp: ELF 64-bit LSB pie executable, ARM aarch64, version 1 ( SYSV) , dynamically linked, interpreter /system/bin/linker64, BuildID[ xxHash]= 8ce9c24e480bcc9d, not stripped
附录
参考文献
NDK下载链接
Android SDK
版权信息
本文原载于 nightrainmilkyway.cn ,遵循 CC BY-NC-SA 4.0 协议,复制请保留原文出处。