使用CMake编译native代码

从AndroidStudio2.2版本开始,官方新增了并默认使用cmake为Android的ndk编译方式。

如何使用?

新建Android工程,勾选C++支持,即可新建一个标准的native开发工程。

其中“CMakeLists.txt”为cmake编译的配置文件

在项目model app的“build.gradle”文件里面,我们可以看到以下代码

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.dvlee.nativedemo"
        minSdkVersion 24
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11"
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

其中,path "CMakeLists.txt"设置了cmake配置文件的路径

然后,我们打开CMakeLists.txt看看

cmake_minimum_required(VERSION 3.4.1)

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 )

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} )

cmake_minimum_required(VERSION 3.4.1)定义cmake的版本

add_library创建native库,定义库的名称、类型和路径,类型包括STATIC和SHARED,分别是静态库和动态库。Gladle会自动打包native库加到APK里面。

find_library定义第三方引用库的名称。这里引用log库,命名为“log-lib”

target_link_libraries链接第三方引用库,即“find_library”里面定义的“log-lib”

cmake编译后的路径为"build/intermediates/cmake/release/obj/arm64-v8a/libnative-lib.so"

其他语法

project (HELLO)指定项目名称,生成的VC项目的名称

set(LIB_NAME NativeLib)定义引用,这句表示把“LIB_NAME”定义为“NativeLib”

${LIB_NAME}引用上面定义的“LIB_NAME”

add_subdirectory添加其他路径的CMakeLists.txt文件

include_directories 、target_include_directories都为引用头文件
两者区别:https://stackoverflow.com/questions/31969547/what-is-the-difference-between-include-directories-and-target-include-directorie
大致意思是,include_directories 的引用范围是cmakelist下的所有target,包括subdirectory;而target_include_directories只是针对当前target,而且还能设置PRIVATE、PUBLIC、INTERFACE。

add_definitions("-DHAVE_NEON=1")设置宏HAVE_NEON

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DvLee1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值