我试图给出一些解释来确定 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 文件的相对路径。