配置和环境:
macOS 10.13.6, cmake 3.10.2, Android Studio 3.2
继 [Note] CMake的简单使用,CMake在Android Studio中的简单使用
一 对比常规创建和C++ Support创建的文件差异
分别以常规创建和C++ Support
创建两个Android Studio
项目:CMakeTest
和 CMakeTest2
,并执行Make Project
后它们之间的差异:
普通方式创建的项目可以补充差异部分文件和配置,主要是
CMakeLists.txt
cpp目录
build.gradle
二 在 AS 中编译一个静态/动态库
在 cpp
目录下新建 include
和 src
两个目录,用来存放头文件和源码;新建 a.h
和 a.cpp
并编辑 CMakeLists.txt
(这里介绍一个骚操作:拆分源码视图,同时展现多个文件内容)
现在来看,跟前面一篇文章中差不多的嘛 ~
三 连接静态/动态库
这里我就就地取材,就拿刚刚输出的库来做例子,我们拷贝 cmake
文件夹中的 liba.so
到 libs
文件夹,注意区分abi
,还有就是不要拷贝libnative-lib.so
,因为会发生冲突!
使用我们的库中的方法,也就是编辑 native-lib.cpp
接着就是修改CMakeLists.txt
,主要是# link a third part lib
这里
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
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)
#add_library( # Sets the name of the library.
# a
#
# # Sets the library as a shared library.
# SHARED
#
# # Provides a relative path to your source file(s).
# src/main/cpp/include/a.h src/main/cpp/src/a.cpp)
# link a third part lib
add_library(a
SHARED
IMPORTED)
set_target_properties( # Specifies the target library.
a
# Specifies the parameter you want to define.
PROPERTIES IMPORTED_LOCATION
# Provides the path to the library you want to import.
${CMAKE_CURRENT_SOURCE_DIR}/libs/${ANDROID_ABI}/liba.so)
include_directories(src/main/cpp/include)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
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)
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
native-lib
a
# Links the target library to the log library
# included in the NDK.
${log-lib})
最后,还需要修改 build.gradle
,把我们的库打包到apk
当中
简单的使用到这里就完结了,关于 CMake
在 AS 中的使用当然不只是这些内容,笔者也在不断探讨中 。
另外地,使用 Android.mk
的方式编译,可以参考 Android JNI Demo
本文项目源码已经上传 https://github.com/AnterGitHub/CMakeTest