【初体验】macos下android ndk交叉编译hello world,并拷贝到android手机上执行

1.机器上以前安装了java 1.8(貌似android ndk不需要java)

2. 下载android ndk,版本是android-ndk-r14b

    (比较奇怪,我下载了最新的android-ndk-r19c,里面找不到交叉编译的gcc命令 )

     (同时还尝试了arm官网提供的gcc,但是这个版本缺乏对应的链接库:https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm)

1 wget https://dl.google.com/android/repository/android-ndk-r14b-darwin-x86_64.zip
2 unzip android-ndk-r14b-darwin-x86_64.zip
3 cd android-ndk-r14b/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/bin

写一个最简单的hello_world程序:

1 //hello.c
2 #include <stdio.h>
3  
4 int main() {
5   printf("hello,world!
");
6   return 0;
7 }

编译和链接命令行:

arm-linux-androideabi-gcc -o hello_arm2 hello.c -pie -fPIC --sysroot=/Users/ahfu/code/android/android-ndk-r14b/platforms/android-22/arch-arm/

#注意 -pie这个参数要加,否则运行出现这样的信息

./hello_arm1
"./hello_arm1": error: Android 5.0 and later only support position-independent executables (-fPIE).

3.下载android tools,使用里面的adb工具来执行:

wget https://dl.google.com/android/repository/platform-tools-latest-darwin.zip

     (其他的平台请参考这篇帖子:https://www.xda-developers.com/install-adb-windows-macos-linux/)

unzip platform-tools-latest-darwin.zip

cd platform-tools

用数据线连接android手机到mac电脑,打开手机的USB调试模式。

adb的命令列表请看:https://developer.android.com/studio/command-line/adb?gclid=EAIaIQobChMIu4nq4oCE4gIVVT5gCh0hggytEAAYASAAEgILkvD_BwE

#以下是实操

adb devices

    手机上显示是否允许USB调试,点击允许

adb root

adb push hello /data/data

adb shell

     cd /data/data

     chmod +x hello

     ./hello  #执行成功 

注意:
1.一定要使用root过的手机

2.只有/data 和 /system/bin 目录有执行权限 

原文地址:https://www.cnblogs.com/ahfuzhang/p/10816075.html