Android sdtuio 在已有的项目中添加cmakelist 编译c

本文详细介绍了如何在Android Studio中进行NDK集成,通过CMakeLists.txt配置C++库,并创建了一个简单的JNI(Java Native Interface)示例,展示了如何从Java调用C++代码。步骤包括在build.gradle中配置cmake,设置NDK版本,创建CMakeLists.txt文件,编写C++代码以及编译和测试。

一、在app buidlgradle中的android如下代码
externalNativeBuild {
cmake {
path “src/main/cpp/CMakeLists.txt”
version “3.10.2”
}
}
二、如图操作添加ndk版本,点击工程项目中的右键,点击open module sttings,右侧中间添加ndk版本
三、在路径src/main/cpp/CMakeLists.txt 创建cmakelist.txt,添加内容
cmake_minimum_required(VERSION 3.10.2)
#project(“jniPra1”)

#aux_source_directory(dir VAR) 发现一个目录下所有的源代码文件并将列表存储在一个变量中。
aux_source_directory(. src_file_list)
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_file_list} )

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 )

target_link_libraries( # Specifies the target library.
native-lib

                   # Links the target library to the log library
                   # included in the NDK.
                   ${log-lib} )

四、创建一个main.cpp文件,如
#include <jni.h>
#include
extern “C” JNIEXPORT jstring JNICALL
Java_com_iflytek_jnipra1_MainActivity_getNativeString(
JNIEnv* env,
jobject /* this */) {
std::string hello = “happy,jni is easy”;
return env->NewStringUTF(hello.c_str());
}
注意需要将Java_com_iflytek_jnipra1_MainActivity修改自己当前所在的类
五、编译运行测试即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值