CMakeLists.txt文件说明
CMakeLists.txt
就是编译so库的脚本文件,类似于原来的Android.mk,Application.mk。
设置CMake插件的版本
# 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.
#语法,参考:https://cmake.org/cmake/help/latest/command/add_library.html
add_library(<name> [STATIC | SHARED | MODULE]
[EXCLUDE_FROM_ALL]
source1 [source2 ...])
# 语法#########################################
# 示例
add_library(
#编译生成的库的名称,注意最终生成时会在前面加`lib`.
# Specifies the name of the library.
native-lib
# Sets the library as a shared library.
# 生成的库的类型,有SHARED,STATIC,MODULE
SHARED
# Provides a relative path to your source file(s).
# 要编译的源代码文件
src/main/cpp/native-lib.cpp )
包含要编译的源码头文件
如果有源码文件有头文件,自然需要包含:
# 语法, 参考:https://cmake.org/cmake/help/latest/command/include_directories.html
include_directories([AFTER|BEFORE] [SYSTEM] dir1 [dir2 ...])
# 语法#########################################
# Specifies a path to native header files.
# 注意这里指定的是头文件的目录
include_directories(src/main/cpp/include/)
使用NDK中的Api
有时候我们发现需要使用到NDK中定义的Api,因为NDK中的API都已经是编译好的,而且CMake
会自动去NDK目录中查找这些我们需要使用的库,所以这里只需要提供库的名称就可以了,一下举例加载NDK中的log库,因为我们在NDK开发中,总是少不了要打印日志的。
- 首先查找要使用的库,使用变量保存它的路径。
# 语法,参考:https://cmake.org/cmake/help/latest/command/find_library.html
# A short-hand signature is:
# name1 保存库路径的变量
find_library (<VAR> name1 [path1 path2 ...])
# The general signature is:
find_library (
<VAR>
name | NAMES name1 [name2 ...] [NAMES_PER_DIR]
[HINTS path1 [path2 ... ENV var]]
[PATHS path1 [path2 ... ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[NO_DEFAULT_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_CMAKE_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_SYSTEM_PATH]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH]
)