- 关于C/C++在AndroidStudio中编程的代码提示问题:
- 使用
cmake配合CMakeLists.txt脚本进行编译的C/C++编程要将源码文件在CMakeLists.txt中添加到工程中才会有对应的代码提示
- 使用
- 关于导入外部的
.so库,并在native代码中调用的问题build.grale的配置
android{ defaultConfig{ externalNativeBuild { cmake{ abiFilters "armeabi-v7a", "arm64-v8a" } } sourceSets { main { jniLibs.srcDirs = ['libs'] } } } externalNativeBuild { cmake { path "CMakeLists.txt" } } ... }- 注意:
sourceSets必须配置,不然在运行时会抛出java.lang.UnsatisfiedLinkError: dlopen failed: library "xxx.so" not found的异常
CMakeLists.txt的编写- 注意这里关于
LIB_DIR的定义,在CMakeLists.txt中编译系统会传入诸多的变量,我们可以在cmake脚本中可以使用,比如这里的CMAKE_CURRENT_SOURCE_DIR表示的就是脚本所在目录,ANDROID_ABI表示的就是打包对应的ABI等等 - 使用预编译好的
.so库的时候需要将.so在脚本中导入并作为依赖通过target_link_libraries设置给目标项目,这里引入的方式是通过add_library与set_target_properties两个方法配合
cmake_minimum_required(VERSION 3.4.1) #project(pngCompress) set(SRC_DIR src/main/jni) set(LIB_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libs/${ANDROID_ABI}) include_directories(${SRC_DIR}/include) add_library(libpng SHARED IMPORTED) set_target_properties(libpng PROPERTIES IMPORTED_LOCATION ${LIB_DIR}/libpng.so) add_library(pngcompress SHARED ${SRC_DIR}/pngcompress.cpp) find_library( 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. pngcompress # Links the target library to the log library # included in the NDK. ${log-lib} libpng)- 注意这里关于