CMakeList.txt详解
CMakeListsts.txt详解
当你使用add_library,添加一个源文件或者库时,为了确保 CMake 可以在编译时定位到你的头文件,最好添加include_directories 命令到 CMake 构建脚本中并指定头文件的路径:
add_library(...) # Specifies a path to native header files. include_directories(src/main/cpp/include/)
如果您在构建脚本中指定“native-lib”作为共享库的名称,CMake 将创建一个名称为 libnative-lib.so
的文件。不过在 Java 代码中加载此库时,请使用您在 CMake 构建脚本中指定的名称:
static { System.loadLibrary(“native-lib”); }
- 添加NDK API
由于 NDK 库已经是 CMake 搜索路径的一部分,您不需要在CMakeLists.txt指定库的位置 - 只需要向CMake 提供您希望使用的库的名称,并将其关联到您自己的原生库中。 find_library命令,从NDK API查找指定名称的库,并为该库赋予一个名称,该名称可以在构建脚本中的其他地方引用,以下是引用log库的示例
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命令关联该库:
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} )
NDK中还包含源代码形式的库,在构建和关联原生库时,如果需要使用这些代码。您可以使用 CMake 构建脚本中的add_library 命令,将源代码编译到原生库中。但是需要要提供该库的路径,您可以使用 ANDROID_NDK
路径变量,Android Studio 会自动为您定义此变量。示例
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} )
- 添加预构建库(prebuild)
添加预构建库与添加原生库类似。不过由于库已经预先构建,您需要使用imported告知CMake 您只希望将库导入到项目中:
add_library( imported-lib SHARED IMPORTED )
然后,您需要使用set_target_properties命令指定库的路径,如下所示。如果该库有多个ABI版本,你可以使用ANDROID_ABI
路径变量
add_library(...) set_target_properties( # Specifies the target library. imported-lib # Specifies the parameter you want to define. PROPERTIES IMPORTED_LOCATION # Provides the path to the library you want to import. imported-lib/src/${ANDROID_ABI}/libimported-lib.so )
为了确保 CMake 可以在编译时定位到头文件,您需要使用include_directories命令,包含头文件的路径:
include_directories( imported-lib/include/ )
要将预构建库关联到您自己的原生库中,请将其添加到 CMake构建脚本的target_link_libraries命令中:
target_link_libraries( native-lib imported-lib app-glue ${log-lib} )
在您构建应用时,Gradle 会自动将导入的库打包到 APK 中。您可以使用APK Analyzer验证Gradle中将哪些库打包到您的APK中。
常用命令
- include_directories #设置头文件搜索路径
- aux_source_directory #将当前目录下所有源文件存储在指定列表中
- link_directories #库路径
- cmake_minimum_required #指定最小版本
#DEFAULT的编译选项是 CMAKE_C_FLAGS
# 指定编译参数
#SET(CMAKE_CXX_FLAGS "-Wno-error=format-security -Wno-error=pointer-sign")
#设置生成的SO动态库最后输出的路径
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/jniLibs/${ANDROID_ABI})
更多命令:https://cmake.org/cmake/help/latest/manual/cmake-commands.7.html