我试图给出一些解释,以确定CMake和NDK-Build和设置之间的不同:
一些初步说明:
Android Studio的本机库默认构建工具是CMake。
Android Studio还支持ndk-build,因为大量现有项目使用构建工具包来编译其本机代码。
如果要创建新的本机库,则应使用CMake。
由于存在大量遗留项目,因此包括对ndk-build的支持。
CMake的:
与Gradle一起工作的外部构建工具,用于构建本机库。 如果您只打算使用ndk-build,则不需要此组件。 CMake需要构建脚本才能知道如何构建本机库。 对于新项目,Android Studio会创建一个CMake构建脚本CMakeLists.txt ,并将其放在模块的根目录中。
如果您的本机源代码还没有CMake构建脚本,则需要自己创建一个脚本并包含相应的CMake命令。 CMake构建脚本是纯文本文件,您必须将其命名为CMakeLists.txt。
# Sets the minimum version of CMake required to build your native library.
# This ensures that a certain set of CMake features is available to
# your build.
cmake_minimum_required(VERSION 3.4.1)
# Specifies a library name, specifies whether the library is STATIC or
# SHARED, and provides relative paths to the source code. You can
# define multiple libraries by adding multiple add.library() commands,
# and CMake builds them for you. When you build your app, Gradle
# automatically packages shared libraries with your APK.
add_library( # Specifies 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/file_name.cpp )
NDK-构建:
Android Studio还支持ndk-build,因为大量现有/遗留项目使用构建工具包来编译其本机代码。 您需要自己创建一个并包含适用于ndk-build的相应Android.mk文件,然后需要为ndk-build配置与CMake相同的gradle文件。
为CMake和ndk-build配置Gradle:
要手动配置Gradle链接到本机库,需要将externalNativeBuild块添加到模块级build.gradle文件,并使用cmake或ndkBuild块进行配置:
android {
...
defaultConfig {
...
// This block is different from the one you use to link Gradle
// to your CMake or ndk-build script.
externalNativeBuild {
// For ndk-build, instead use the ndkBuild block.
cmake/ndkBuild {
// Passes optional arguments to CMake.
arguments "-DANDROID_ARM_NEON=TRUE", "-DANDROID_TOOLCHAIN=clang"
// Sets optional flags for the C compiler.
cFlags "-fexceptions", "-frtti"
// Sets a flag to enable format macro constants for the C++ compiler.
cppFlags "-D__STDC_FORMAT_MACROS"
}
}
ndk {
// Specifies the ABI configurations of your native
// libraries Gradle should build and package with your APK.
abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'arm64-v8a'
}
}
buildTypes {...}
// Encapsulates your external native build configurations.
externalNativeBuild {
// Encapsulates your CMake build configurations.
cmake {
// Provides a relative path to your CMake build script.
path "src/main/cpp/CMakeLists.txt"
}
// Encapsulates your ndkBuild build configurations.
ndkBuild {
// Provides a relative path to your ndkBuild Android.mk file.
path "src/main/cpp/Android.mk"
}
}
}
如果要将Gradle链接到现有的ndk-build项目,请使用ndkBuild块而不是cmake块,并提供Android.mk文件的相对路径。