本文简介:
最近看了一些文章,看到大部分关于Android jni的配置都还是ndkBuild模式的;有的则是说怎么引用已经编译好的os文件。本文主要以一个小dome为列,记录Android jni cmake模式下的配置。
一、环境配置
Android 开发的环境配置网上已经很多了,这里就不重复。我们做jni开发的,需要用到snk,所以我们第一步,在Android studio 上引入ndk
这里我们主要需要勾选NDK、CMake。为啥要勾选CMake因为我们自己常常用传统方法生成,配置太过于麻烦,所以我们这里用CMake,直接生成一个标准的例子,进行修改。这样就会减少很多问题的产生,节省我们的时间。
二、项目创建
(一)首先创建新项目,选择创建NativityC++项目
(二)填写项目信息。
选择对c++标准,这里选择的默认。
(三)创建成功后项目架构是如下图
三、与Android项目有些差别及说明
(一)app下的build.gradle
这里多了些关于编译ndk的入口配置数据
externalNativeBuild {
cmake {
cppFlags ""
}
}
这里的cppFlags 值为引用的其他类库比如:
cppFlags "-fexceptions"
编译snk异常捕获的
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
version "3.10.2"
}
}
path :指定编译的目标配置文件地址
version:编译版本的
(二)结构上:
main下面多了cpp的包,里面有多了一个CMakeLists.txt和native-lib.cpp
这两个文件,CMakeLists.txt是关于cmake的一些基础配置和编译ndk的文件关联配置
native-lib.cpp则是C++将要编译的代码文件
1、首先看CMakeLists.txt的内容:
# 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).
native-lib.cpp)
# 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_librari