配置CMake
在Android Studio中进行NDK开发,需要配置Cmake。在jni工程中使用CMakeLists.txt文件进行配置。
在配置的头部,指明Cmake的最低版本
cmake_minimum_required(VERSION 3.4.1)
构建Debug和Release版本可使用以下语句区分
IF (CMAKE_BUILD_TYPE MATCHES "Debug" OR CMAKE_BUILD_TYPE MATCHES "None") add_definitions(-DENABLE_LOG) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -s") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fvisibility=hidden") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ffunction-sections -fdata-sections -Wl,--gc-sections") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffunction-sections -fdata-sections -Wl,--gc-sections") ELSEIF (CMAKE_BUILD_TYPE MATCHES "Release") add_definitions(-DENABLE_LOG) add_definitions(-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fvisibility=hidden") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ffunction-sections -fdata-sections -Wl,--gc-sections") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffunction-sections -fdata-sections -Wl,--gc-sections") ELSE () MESSAGE(STATUS "unknown CMAKE_BUILD_TYPE = " ${CMAKE_BUILD_TYPE}) ENDIF ()
对so库进行裁剪符号信息
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -s") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s")
添加头文件目录
include_directories(${CMAKE_SOURCE_DIR}/include)
包含其他CMake项目,编译脚本使用 add_subdirectory() 命令将另一个 CMakeLists.txt 文件指定为编译依赖项,然后关联其输出,就像处理任何其他预编译库一样。
# Adds the CMakeLists.txt file located in the specified directory # as a build dependency. add_subdirectory( # Specifies the directory of the CMakeLists.txt file. ${lib_src_DIR} # Specifies the directory for the build outputs. ${lib_build_DIR} )
在其他项目中,可以编译成静态库,如
add_library( # Sets the name of the library. testone # Sets the library as a shared library. STATIC # Provides a relative path to your source file(s). one.c)
也可以编译成动态库引入,如
add_library( # Sets the name of the library. testtwo # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). two.c)
在主Cmake项目中这样引用
add_subdirectory(${CMAKE_SOURCE_DIR}/testone) add_subdirectory(${CMAKE_SOURCE_DIR}/testtwo) add_library( main SHARED main.c) target_link_libraries( # Specifies the target library. main testone testtwo)
如果要引用一个已编译好的静态库,则是
add_library(staticone STATIC IMPORTED) set_target_properties(staticone PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/server/lib/${ANDROID_ABI}/libstaticone.a)
想要修改编译的指定abi,则需要修改app的build.gradle中的defaultConfig,添加下面脚本
ndk { // Specifies the ABI configurations of your native // libraries Gradle should build and package with your APK. abiFilters 'armeabi-v7a','arm64-v8a' }
要包含Cmake项目中的Cmake配置,则在app的build.gradle中的defaultConfig同级上添加
externalNativeBuild { cmake { path "src/main/cpp/CMakeLists.txt" version "3.10.2" } }
配置Android.mk
- 本文固定链接: https://freemanapp.com/zh/?p=767
- 转载请注明: freeman 于 FreemanApp 发表