Android NDK Makefile相关与示例

本文最后更新于:2023年4月15日 下午

Android.mkApplication.mk

Android Studio 3之前,需要编写Android.mkApplication.mk文件。

使用jdk8或jdk7中提供的javah来生成头文件。

build.gradle设定jni

以下是某模块的build.gradle文件

1
2
3
4
5
6
7
android {
// ....
sourceSets.main {
jni.srcDirs = [] // 禁止自动执行ndk-build
jniLibs.srcDirs = ['src/main/libs'] // 设定成so文件生成的目录
}
}

指定模块的名字

Android.mk文件中指定模块的名字

1
LOCAL_MODULE := modname

编译得到libmodname.so文件

加载库文件

1
2
3
static {
System.loadLibrary("modname");
}

利用$(TARGET_ARCH_ABI)判断目标架构类别

Android Studio 3之前,需要编写Android.mkApplication.mk文件。使用jdk8或jdk7。

一个典型Application.mk

1
2
3
4
APP_ABI := arm64-v8a armeabi-v7a
APP_PLATFORM := android-19
APP_STL := gnustl_static
APP_CPPFLAGS += -std=c++11

指定了2种架构

Android.mk中,可以用$(TARGET_ARCH_ABI)判断目标架构类别;
例如jni目录中有如下的文件

1
2
3
4
5
6
7
8
9
10
11
jni
|-- Android.mk
|-- Application.mk
|-- something.cpp
|-- include
| |-- something.h
|-- lib
| |-- arm64-v8a
| | `-- libcustom.a
| `-- armeabi-v7a
| `-- libcustom.a

Android.mk中判断当前编译的目标架构而加载库文件libcustom.a

1
LOCAL_LDFLAGS := $(LOCAL_PATH)/lib/$(TARGET_ARCH_ABI)/libcustom.a

引用OpenCV模块

假设已经下载好opencv-3.2.0SDK,Android.mk中引用

1
2
3
4
5
6
OPENCVROOT:=$(LOCAL_PATH)/../../../../../opencv-3.2.0-android-sdk/OpenCV-android-sdk
OPENCV_CAMERA_MODULES:=off
OPENCV_INSTALL_MODULES:=on
OPENCV_LIB_TYPE:=STATIC

include ${OPENCVROOT}/sdk/native/jni/OpenCV.mk

使用相对路径找到sdk,引入OpenCV的mk文件

Android NDK 通用 makefile 与相关配置

Android.mk

1
2
3
4
5
6
7
8
9
10
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := waveExtract
TARGET_ARCH_ABI := all

LOCAL_SRC_FILES := src/wave_display.c src/FFT.c

LOCAL_LDLIBS+= -L$(SYSROOT)/usr/lib -llog

include $(BUILD_SHARED_LIBRARY)


Application.mk

1
2
3
4
5
6
7
APP_PLATFORM := android-19
APP_MODULES := waveExtract
APP_ABI := armeabi-v7a arm64-v8a
APP_STL := stlport_static
APP_CPPFLAGS += -fexceptions
# for using c++ features,you need to enable these in your Makefile
APP_CPP_FEATURES += exceptions rtti


build.gradle

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
apply plugin: 'com.android.library'

android {
compileSdkVersion 28

defaultConfig {
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}

sourceSets {
main {
jni.srcDirs = []
jniLibs.srcDirs = ['src/main/libs']
}
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation 'com.android.support:appcompat-v7:28.+'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


Android NDK Makefile相关与示例
https://blog.rustfisher.com/2018/05/21/Android/NDK-Makefile_example/
作者
Rust Fisher
发布于
2018年5月21日
许可协议