我试图给出一些解释来识别CMake和NDK-Build与setup之间的区别:
一些初步的注意事项:
Android Studio用于本机库的默认构建工具是CMake。
由于存在大量使用构建工具包来编译其本机代码的现有项目,因此Android Studio还支持ndk-build。
如果要创建新的本机库,则应使用CMake。
由于存在大量旧项目,因此包括对ndk-build的支持。
CMake的:
一个与Gradle一起使用的外部构建工具,以构建您的本机库。 如果仅计划使用ndk-build,则不需要此组件。 CMake需要一个构建脚本来知道如何构建您的本机库。 对于新项目,Android Studio将创建CMake构建脚本ndkBuild,并将其放置在模块的根目录中。
如果您的本地源还没有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链接到您的本机库,您需要将ndkBuild块添加到模块级Android.mk文件中,并使用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文件的相对路径。