美文网首页Android
将原有Android项目转成NDK项目

将原有Android项目转成NDK项目

作者: o_30ca | 来源:发表于2019-12-23 14:58 被阅读0次

将原有Android项目转成ndk项目

本文所描述的是3.0版本及以上Android Studio

首先3.0之后新增了cmake插件,所以我们需要的是新增CMakeLists.txt

然后我们需要的是关联,在相应的模块包的build.gradle下面添加以下代码:

externalNativeBuild {

        cmake {

            path "src/main/cpp/CMakeLists.txt"//这里填自己新建的路径

            version "3.10.2"

       }

}

但是现在会出现一个问题,就是我们没有指定c++的版本还有我们本地并没有相关ndk的头文件和jni的头文件,怎么办?

首先我们可以指定c++的版本,还是在相应模块下的build.gradle中添加:

externalNativeBuild {

            cmake {

                cppFlags ""

            }

        }

不过这次的位置不是和上次一样的,上次是在Android的父级,这个是defaultConfig父级,cppFlags后面的引号不写的话就是自适应的版本,后面像指定版本需要添加:-std=c++14,

我的完整build.gradle

这样build.project的配置就完成了

现在的问题就是我们需要添加相应的ndk头文件和实现文件

需要在cmake文件里面添加以下代码:

# 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(

              #你可以自定义的动态库名字

             native-lib

             # Sets the library as a shared library.

             SHARED

             #你写好的cpp文件

            main.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_libraries( # Specifies the target library.

                       #你想添加的动态库名字

                        native-lib

                       # Links the target library to the log library

                       # included in the NDK.

                       ${log-lib} )

Make一下即可

相关文章

网友评论

    本文标题:将原有Android项目转成NDK项目

    本文链接:https://www.haomeiwen.com/subject/avvznctx.html