ARM 版的Clang的使用

2,277 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

image.png 在mac环境有个原生的Clang,但是它编译的文件生成的平台不能用于手机上使用,也就是不能生成ARM架构的,如果想在电脑生成手机上能运行的可执行文件,可以用NDK目录下的clang,最简单的方式就是安装个android studio 然后安装ndk,一般安装的时候应该有提示之类。

安装

android studio下面ndk目录的clang,为了方便后面使用我这里把它配置成了系统的环境变量, 我使用的zsh配置,之后编译即可。

export PATH="/Users/chennan/Library/Android/sdk/ndk/21.3.6528147/toolchains/llvm/prebuilt/darwin-x86_64/bin:$PATH"

也可以在这个页面找到developer.android.com/ndk/guides/…

执行命令

clang -target后面加要生成可执行文件的运行平台,因为我们要在手机上使用所以选择

预编译

clang -target arm-linux-android21 -E hello.c -o hello.i

执行平台和对应参数关系如表

ABI三元组
armeabi-v7aarmv7a-linux-androideabi
arm64-v8aaarch64-linux-android
x86i686-linux-android
x86-64x86_64-linux-android

预编译的文件,就是将导入的头文件以及宏展开。

编译

clang -target arm-linux-android21 -S hello.i -o hello.s

这一步生成.S的汇编文件

汇编

clang -target arm-linux-android21 -c hello.s -o hello.o

也可以将汇编文件直接编译成可执行文件

clang -target arm-linux-android21 arm_hello.s -o arm_hello

arm_hello.s是hello.s的一个副本,删除了一些伪代码和注释以及对结果影响不大的代码。

链接

有的时候会生成多个o文件,这个时候需要将他们链接起来生成可执行文件

clang -target arm-linux-android21 hello.o -o hello

之后可以将文件push到手机里面执行了。

如果不需要了解中间过程可以执行下面命令,直接生成可执行的文件。

clang -target arm-linux-android21 hello.c -o hello

安装手机执行

之后就可以push到手机上执行了。

adb push hello /data/local/tmp/.
adb shell
./data/local/tmp/hello