从AndroidStudio2.2版本开始,官方新增了并默认使用cmake为Android的ndk编译方式。
如何使用?
新建Android工程,勾选C++支持,即可新建一个标准的native开发工程。
其中“CMakeLists.txt”为cmake编译的配置文件
在项目model app的“build.gradle”文件里面,我们可以看到以下代码
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.dvlee.nativedemo"
minSdkVersion 24
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags "-std=c++11"
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
其中,path "CMakeLists.txt"
设置了cmake配置文件的路径
然后,我们打开CMakeLists.txt看看
cmake_minimum_required(VERSION 3.4.1)
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 )
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 )
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib} )
cmake_minimum_required(VERSION 3.4.1)
定义cmake的版本
add_library
创建native库,定义库的名称、类型和路径,类型包括STATIC和SHARED,分别是静态库和动态库。Gladle会自动打包native库加到APK里面。
find_library
定义第三方引用库的名称。这里引用log库,命名为“log-lib”
target_link_libraries
链接第三方引用库,即“find_library”里面定义的“log-lib”
cmake编译后的路径为"build/intermediates/cmake/release/obj/arm64-v8a/libnative-lib.so"
其他语法
project (HELLO)
指定项目名称,生成的VC项目的名称
set(LIB_NAME NativeLib)
定义引用,这句表示把“LIB_NAME”定义为“NativeLib”
${LIB_NAME}
引用上面定义的“LIB_NAME”
add_subdirectory
添加其他路径的CMakeLists.txt文件
include_directories 、target_include_directories
都为引用头文件
两者区别:https://stackoverflow.com/questions/31969547/what-is-the-difference-between-include-directories-and-target-include-directorie
大致意思是,include_directories 的引用范围是cmakelist下的所有target,包括subdirectory;而target_include_directories只是针对当前target,而且还能设置PRIVATE、PUBLIC、INTERFACE。
add_definitions("-DHAVE_NEON=1")
设置宏HAVE_NEON