android ndk开发可以通过ndk-build、CMake以及独立工具链三种方式来进行构建,本文主要讲解通过CMake构建ndk。
首先下载SDK-Tools中的CMake、LLDB、NDK三个工具。
早期as版本创建项目时记得选择Include C++ support选项,
后面版本(貌似as3.1以后吧)选择Native C++选项。
后面一路next就可以创建带有cpp源文件、CMakeLists.txt配置文件的简单android ndk项目。
CMakeLists.txt文件如下:
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/native-lib.cpp )
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib} )
add_library 表示创建库,库名native-lib,共享库SHARED,源文件src/main/cpp/native-lib.cpp。
find_library表示依赖的预编译库。
target_link_libraries表示链接目标库native-lib到CMake。
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.ndk.ndk"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags "-frtti -fexceptions"
}
}
ndk{
abiFilters "armeabi-v7a"
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
由于android studio使用gradle构建文件,所以CMakeLists.txt最终还是在gradle文件中应用的。module.gradle文件有两个地方配置了ndk.
defaultConfig内的ndk配置了支持的属性cppFlags以及abi类型,defaultConfig外指明了CMakeLists.txt路径。
参考:Android JNI学习(二)——实战JNI之“hello world”