AndroidStudio3.*+ jni 开发配置cmake模式

本文介绍了如何在Android Studio 3.x中使用CMake配置JNI开发环境。通过创建一个新的原生C++项目,详细讲解了环境配置、项目创建、CMakeLists.txt的修改、Java代码的调整以及C/C++代码的实现,包括如何处理回调方法。并提供了项目实例链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文简介:
  最近看了一些文章,看到大部分关于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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值