一、ndk下载
NDK 下载 | Android NDK | Android Developers
二、ndk环境变量配置
ndk解压:
unzip android-ndk-r26d-linux.zip
环境变量配置:
export NDK_HOME=/rd/own/test/android-ndk-r26d/
export PATH=$PATH:$NDK_HOME
三、编译测试验证
3.1 程序创建
创建helloworld, 在其下创建jni目录,并准备好hello.c和Android.mk
rd@ubuntu:~/test/android-ndk-r26d$ cat helloword/jni/hello.c
#include <stdio.h>
int main (int argc,char *argv[])
{printf("hello world!");return 0;
}
rd@ubuntu:~/test/android-ndk-r26d$ cat helloword/jni/Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := helloworld
LOCAL_SRC_FILES := hello.c
#include $(BUILD_SHARED_LIBRARY)
include $(BUILD_EXECUTABLE)
编译库文件Android.mk参考:
LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_MODULE := FRE
LOCAL_SRC_FILES := FlashRuntime.so
include $(PREBUILT_SHARED_LIBRARY)include $(CLEAR_VARS)LOCAL_MODULE := NativeQCAR
LOCAL_SRC_FILES := main.c
LOCAL_SHARED_LIBRARIES := FRE
include $(BUILD_SHARED_LIBRARY)
备注:如果不创建jni目录,会报NDK_PROJECT_PATH 找不到。
Android NDK: Could not find application project directory !
Android NDK: Please define the NDK_PROJECT_PATH variable to point to it.
如果不创建jni目录,则需要添加额外的配置( NDK_PROJECT_PATH、NDK_APPLICATION_MK和APP_BUILD_SCRIP),如下:
ndk-build NDK_PROJECT_PATH=/rd/test/android-ndk-r26d/helloword NDK_APPLICATION_MK=/rd/test/android-ndk-r26d/Application.mk
cat Application.mk
APP_BUILD_SCRIPT := /rd/test/android-ndk-r26d/helloword/Android.mk
3.2 编译过程
~/test/android-ndk-r26d/build/ndk-build
Android NDK: APP_PLATFORM not set. Defaulting to minimum supported version android-21.
[arm64-v8a] Compile : helloworld <= hello.c
[arm64-v8a] Executable : helloworld
[arm64-v8a] Install : helloworld => libs/arm64-v8a/helloworld
[armeabi-v7a] Compile thumb : helloworld <= hello.c
[armeabi-v7a] Executable : helloworld
[armeabi-v7a] Install : helloworld => libs/armeabi-v7a/helloworld
[x86] Compile : helloworld <= hello.c
[x86] Executable : helloworld
[x86] Install : helloworld => libs/x86/helloworld
[x86_64] Compile : helloworld <= hello.c
[x86_64] Executable : helloworld
[x86_64] Install : helloworld => libs/x86_64/helloworld
3.3 编译结果,默认会编译出不同架构的可执行文件
./helloword/libs/arm64-v8a/helloworld
./helloword/libs/x86/helloworld
./helloword/libs/x86_64/helloworld
./helloword/libs/armeabi-v7a/helloworld
./helloword/obj/local/arm64-v8a/objs/helloworld
./helloword/obj/local/arm64-v8a/helloworld
./helloword/obj/local/x86/objs/helloworld
./helloword/obj/local/x86/helloworld
./helloword/obj/local/x86_64/objs/helloworld
./helloword/obj/local/x86_64/helloworld
./helloword/obj/local/armeabi-v7a/objs/helloworld
./helloword/obj/local/armeabi-v7a/helloworld
3.4 测试执行
adb push helloworld /data
data/helloworld
hello world!
3.5 编译说明
也可选择其他编译选项:
在jni目录或者helloword目录下执行:
ndk-build APP_ABI=all //编译所有平台
ndk-build APP_ABI=armeabi-v7a //编译armv7
ndk-build APP_ABI=mips //编译mips
ndk-build APP_ABI=arm64-v8a //编译armv8A
其他ABI编译参考:build/cmake/abis.cmake
~/test/android-ndk-r26d/build/ndk-build // 默认多架构编译
生成的可执行文件在helloworld/libs或者helloword/obj下,不同平台对应不同的目录。