Android Studio NDK项目编译备忘录

来源:互联网 发布:黑米抢购软件靠谱吗 编辑:程序博客网 时间:2024/05/16 18:46

  新建NDK项目,在AS新建项目时勾选C++ support其他步骤默认选项即可。

  前序知识:

        CMakeList.txt

        build.gradle(Module:app)

 bulid.gradle是负责整个安卓项目编译的脚本。

“Starting in 2.2, Android Studio on 64 bit OS supports building C/C++ via CMake and ndk-build through stable gradle.

In both cases, Gradle is configured to point at the external build system. ”---参考安卓技术文档解释
所以在 build.gradle可以选择CMakeList.txt 或者 Android.mk +Application.mk的方式来支持编译C/C++

    externalNativeBuild {        cmake {             path 'src/main/jni/CMakeLists.txt'        }        //ndkBuild {        //   path 'src/main/jni/Android.mk'        //}    }
这里推荐使用CMake来支持编译。一下是CMakeList.txt 内容:
cmake_minimum_required(VERSION 3.4.1)
指定cmake需要的最低版本,一般由AS默认,不需要更改
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()//配置我们编译的so库信息
native-lib
这个是声明so库的名称,在项目中,如果需要使用这个so文件,加载的库名称就是它。
值得注意的是,实际上生成的so文件名称是libnative-lib。当Run项目或者build项目是,在Module级别的build文件下的intermediates\transforms\mergeJniLibs\debug\folders\2000\1f\main下会生成相应的so库文件。
SHARED
这个参数设置so库的类型。可以是以下值:
STATIC:静态库,是目标文件的归档文件,在链接其它目标的时候使用。
SHARED:动态库,会被动态链接,在运行时被加载。
也就是在Run项目或者build项目时会在目录intermediates\transforms\mergeJniLibs\debug\folders\2000\1f\main下生成so库文。此外,so库文件都会在打包到.apk里面,可以通过选择菜单栏的Build->Analyze Apk...*查看apk中是否存在so库文件,一般它会存放在lib目录下。
MODULE:模块库,是不会被链接到其它目标中的插件,但是可能会在运行时使用dlopen-系列的函数动态链接。
src/main/cpp/native-lib.cpp
构建so库的源文件,可以是多个源文件编译成一个so库
find_library( # Sets the name of the path variable.          android-lib          # Specifies the name of the NDK library that          # you want CMake to locate.          android )
find_library()//设置链接库变量,类似Linux的Shell脚本的Export指定变量名和路径以供其他地方使用
android-lib 变量名
android 需要cmake搜索的其他库
target_link_libraries( # Specifies the target library.                       native-lib                       # Links the target library to the log library                       # included in the NDK.                       ${log-lib}                       ${android-lib})
target_link_libraries()//设置链接库,对于编译native-lib动态库需要链接其他库
native-lib 需要链接的库
${android-lib}表示引用变量android-lib,这个变量在find_libary()是我们自己定义的

到此基本的文件配置完成。



原创粉丝点击