NDk配置 打开Default Preferences ->Appearance & Behavior ->System Settings ->Android SDK ->SDk Tools ->下载Cmake、LLDB、NDK
一、创建支持C/C++的新项目
创建新项目 ->勾上include C++ Support ->C++ Standard选项: 选择 C++ 标准 ->Exceptions Support选项: 是否启用对 C++ 异常处理的支持 ->Runtime Type Information Support选项: 是否支持支持 RTTI
之后Android Studio便会自动创建支持C++的Hello模版
二、在原有项目上支持C/C++
分3步骤 1、创建新的原生文件
->在根目录创建”CMakeLists.txt”
2、创建CMake构建脚本
->添加CMake命令,cmake_minimum_required()和add_library()1
2
3
4
5
6
7
8
9
10
11
cmake_minimum_required(VERSION 3.4.1)
add_library( native-lib
SHARED
src/main/cpp/native-lib.cpp )
add_library()指向源文件,为确保CMake可以定位头文件,需添加 include_directories()
1
2
3
4
add_library(...)
# Specifies a path to native header files.
include_directories(src/main/cpp/include/)
添加NDK API
->日志库1
2
3
4
5
6
7
find_library( # Defines the name of the path variable that stores the
# location of the NDK library.
log-lib
# Specifies the name of the NDK library that
# CMake needs to locate.
log )
为了确保您的原生库可以在 log 库中调用函数,您需要使用 CMake 构建脚本中的 target_link_libraries() 命令关联库:1
2
3
4
5
6
7
8
find_library(...)
# Links your native library against one or more other native libraries.
target_link_libraries( # Specifies the target library.
native-lib
# Links the log library to the target library.
${log-lib} )
为了确保您的原生库可以在 log 库中调用函数,您需要使用 CMake 构建脚本中的 target_link_libraries() 命令关联库:
1
2
3
4
5
6
7
8
find_library(...)
# Links your native library against one or more other native libraries.
target_link_libraries( # Specifies the target library.
native-lib
# Links the log library to the target library.
${log-lib} )
以下命令可以指示 CMake 构建 android_native_app_glue.c,后者会将 NativeActivity 生命周期事件和触摸输入置于静态库中并将静态库关联到 native-lib:1
2
3
4
5
6
add_library( app-glue
STATIC
${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c )
# You need to link static libraries against your shared native library.
target_link_libraries( native-lib app-glue ${log-lib} )
添加其他预构建库
1
2
3
4
5
6
7
8
9
10
11
12
13
add_library( imported-lib
SHARED
IMPORTED )
set_target_properties( imported-lib
PROPERTIES IMPORTED_LOCATION
imported-lib/src/${ANDROID_ABI}/libimported-lib.so )
include_directories( imported-lib/include/ )
target_link_libraries( native-lib imported-lib app-glue ${log-lib} )
3、让Gradle关联原生库
-> 先在app目录下创建CMakeLists.txt,添加cmake_minimum_required(VERSION 3.4.1),add_library(),set_target_properties(),target_link_libraries() ->菜单选中 link C++ support 并关联CMakeLists.txt
tag: NDK