一、什么是CMake
或許聽過好幾種 Make 工具,如 GNU Make ,qmake,MS nmake等。這些 Make 工具遵循著不同的規范和標準,所執行的 Makefile 格式也千差萬別。如果軟件想跨平臺,必須要保證能夠在不同平臺編譯。而如果使用上面的 Make 工具,就得為每一種標準寫一次 Makefile 。
CMake就是針對上面問題所設計的工具,它讓開發者編寫一種平臺無關的 CMakeList.txt 文件來定制整個編譯流程,然后再根據目標用戶的平臺進一步生成所需的本地化 Makefile 和工程文件。
二、CMakeList.txt文件
如上所述,這個文件是用來定制編譯流程的。里面包含的是一些命令。
CMakeLists.txt 的語法比較簡單,由命令、注釋和空格組成,其中命令是不區分大小寫的。符號 # 后面的內容被認為是注釋。命令由命令名稱、小括號和參數組成,參數之間使用空格進行間隔。
如下是AndroidStuido新建項目,默認生成的CMakeList.txt。這里改了些注釋
# Sets the minimum version of CMake required to build the native
# library. You should either keep the default value or only pass a
# value of 3.4.0 or lower.
#最低版本要求
cmake_minimum_required(VERSION 3.4.1)
#添加庫或者源文件,參數1.生成庫的名字 2.生成庫的類型 3.源文件所在路徑
add_library(native-lib SHARED src/main/cpp/native-lib.cpp )
#查找NDK提供的庫,這里是查找用于打印日志的log庫,參數1.給查找庫的別名 2.查找庫的名稱
find_library(log-lib log )
#將預構建的庫和自己的原生庫關聯 參數1.原生庫的名稱 2.預構建庫的別名
target_link_libraries(native-lib ${log-lib} )
更加關于AS下的CMakeList.text內容在Android的官方文檔里
三、在build.gradle里對CMake的一些必要配置
externalNativeBuild {
cmake {
path "CMakeLists.txt"http://指定CMakeLists.txt的路徑
}
}
四、在build.gradle里對CMake的一些可選配置
android {
...
defaultConfig {
...
// This block is different from the one you use to link Gradle
// to your CMake or ndk-build script.
externalNativeBuild {
// For ndk-build, instead use ndkBuild {}
cmake {
// Passes optional arguments to CMake.
arguments "-DCMAKE_VERBOSE_MAKEFILE=TRUE"
// Sets optional flags for the C compiler.
cFlags "-D_EXAMPLE_C_FLAG1", "-D_EXAMPLE_C_FLAG2"
// Sets a flag to enable format macro constants for the C++ compiler.
cppFlags "-D__STDC_FORMAT_MACROS"
}
}
ndk {
// Specifies the ABI configurations of your native
// libraries Gradle should build and package with your APK.
abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'arm64-v8a'
}
buildTypes {...}
productFlavors {
...
demo {
...
externalNativeBuild {
cmake {
...
// Specifies which native libraries to build and package for this
// product flavor. If you don't configure this property, Gradle
// builds and packages all shared object libraries that you define
// in your CMake or ndk-build project.
targets "native-lib-demo"
}
}
}
paid {
...
externalNativeBuild {
cmake {
...
targets "native-lib-paid"
}
}
}
}
// You use this block to link Gradle to your CMake or ndk-build script.
externalNativeBuild {
cmake {...}
// or ndkBuild {...}
}
}