NDK编译系列文章
NDK全称是啥?
Windows平台编译时,需安装Andriod官网下的NDK工具,并配置相关环境变量。对源码,建议按以下目录结构组织构建:
目录结构
jni
libs
obj
jni目录中主要存放编译脚本和代码源文件(放于src目录中)。libs为最终编译构建生成的exe或lib。obj主要存放构建过程中的中间件。
编译流程
andriod.mk源码
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := EXEC_DEMO # exe name
CPP_LIST += $(wildcard $(LOCAL_PATH)/src/demo/*.c)
CPP_LIST += $(wildcard $(LOCAL_PATH)/src/func/*.c)
LOCAL_SRC_FILES := $(CPP_LIST:$(LOCAL_PATH)/%=%)
LOCAL_C_INCLUDES := ./src/demo ./src/func
#cortex-a7, armv7
#cortex-a53, armv8a
LOCAL_CFLAGS += -mfpu=neon -mfloat-abi=softfp -mcpu=cortex-a53 -O2 -fPIC -Wall
LOCAL_CFLAGS += -pie -FPIE
LOCAL_CFLAGS += -DNDK_TEST # 程序宏定义
include $(BUILD_EXECUTABLE) # 生成可执行EXE
#include $(BUILD_SHARED_LIBRARY) # 动态库
#include $(BUILD_STATIC_LIBRARY) # 生成静态库
application.mk源码
#APP_ABI := armeabi
#APP_ABI := armeabi-v7a
APP_ABI := arm64-v8a
#NDK_TOOLCHAIN_VERSION = 4.9
生成动态库的andriod.mk源码
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := demo # libdemo.so
CPP_LIST += $(wildcard $(LOCAL_PATH)/src/demo/*.c)
CPP_LIST += $(wildcard $(LOCAL_PATH)/src/func/*.c)
LOCAL_SRC_FILES := $(CPP_LIST:$(LOCAL_PATH)/%=%)
LOCAL_C_INCLUDES := ./src/demo ./src/func
#cortex-a7, armv7
#cortex-a53, armv8a
LOCAL_CFLAGS += -mfpu=neon -mfloat-abi=softfp -mcpu=cortex-a53 -O2 -fPIC -Wall
LOCAL_CFLAGS += -pie -FPIE
#LOCAL_CFLAGS += -DNDK_DEMO # 宏定义
#include $(BUILD_EXECUTABLE) # 可执行EXE
include $(BUILD_SHARED_LIBRARY) # 动态库
#include $(BUILD_STATIC_LIBRARY) # 生成静态库
application.mk源码
#APP_ABI := armeabi
#APP_ABI := armeabi-v7a
APP_ABI := arm64-v8a
#NDK_TOOLCHAIN_VERSION = 4.9
EXE链接生成的动态库
将上面生成动态库libdemo.so拷贝到exe构建的jni目录下,与脚本目录同级。
andriod.mk源码
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := libso
# v8a
LOCAL_SRC_FILES := libdemo.so
include $(PREBUILT_SHARED_LIBRARY)
#include $(PREBUILT_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := EXEC_DEMO # 最终生成的可执行文件
CPP_LIST += $(wildcard $(LOCAL_PATH)/src/demo/*.c)
CPP_LIST += $(wildcard $(LOCAL_PATH)/src/func/*.c)
LOCAL_SRC_FILES := $(CPP_LIST:$(LOCAL_PATH)/%=%)
LOCAL_C_INCLUDES := $(LOCAL_PATH)/src/demo/ \
$(LOCAL_PATH)/src/func/ \
LOCAL_SHARED_LIBRARIES := libso
#LOCAL_STATIC_LIBRARIES := libso
# v8a
LOCAL_CFLAGS += -mfpu=neon -mfloat-abi=softfp -mcpu=cortex-a53 -O3 -fPIC -Wall
LOCAL_CFLAGS += -pie -FPIE
LOCAL_LDFLAGS += -pie -FPIE
include $(BUILD_EXECUTABLE)
#include $(BUILD_SHARED_LIBRARY)
application.mk源码 无变化
#APP_ABI := armeabi
#APP_ABI := armeabi-v7a
APP_ABI := arm64-v8a
#NDK_TOOLCHAIN_VERSION = 4.9
一切准备就续后,打开cmd,输入指令cd切换到当前jni目录,运行以下指令:
ndk-build --version
,查看NDK版本ndk-build clean
,清理之前编译中间结果ndk-build
,在jni目录下开始编译,生成结果在libs/obj中之后,将生成的exe或lib库,用adb推送到andriod终端,并赋予相关执行权限,即可正常运行测试。