一、什么是CMake
或許聽(tīng)過(guò)好幾種 Make 工具,如 GNU Make ,qmake,MS nmake等。這些 Make 工具遵循著不同的規(guī)范和標(biāo)準(zhǔn),所執(zhí)行的 Makefile 格式也千差萬(wàn)別。如果軟件想跨平臺(tái),必須要保證能夠在不同平臺(tái)編譯。而如果使用上面的 Make 工具,就得為每一種標(biāo)準(zhǔn)寫(xiě)一次 Makefile 。
CMake就是針對(duì)上面問(wèn)題所設(shè)計(jì)的工具,它讓開(kāi)發(fā)者編寫(xiě)一種平臺(tái)無(wú)關(guān)的 CMakeList.txt 文件來(lái)定制整個(gè)編譯流程,然后再根據(jù)目標(biāo)用戶(hù)的平臺(tái)進(jìn)一步生成所需的本地化 Makefile 和工程文件。
二、CMakeList.txt文件
如上所述,這個(gè)文件是用來(lái)定制編譯流程的。里面包含的是一些命令。
CMakeLists.txt 的語(yǔ)法比較簡(jiǎn)單,由命令、注釋和空格組成,其中命令是不區(qū)分大小寫(xiě)的。符號(hào) # 后面的內(nèi)容被認(rèn)為是注釋。命令由命令名稱(chēng)、小括號(hào)和參數(shù)組成,參數(shù)之間使用空格進(jìn)行間隔。
如下是AndroidStuido新建項(xiàng)目,默認(rèn)生成的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)
#添加庫(kù)或者源文件,參數(shù)1.生成庫(kù)的名字 2.生成庫(kù)的類(lèi)型 3.源文件所在路徑
add_library(native-lib SHARED src/main/cpp/native-lib.cpp )
#查找NDK提供的庫(kù),這里是查找用于打印日志的log庫(kù),參數(shù)1.給查找?guī)斓膭e名 2.查找?guī)斓拿Q(chēng)
find_library(log-lib log )
#將預(yù)構(gòu)建的庫(kù)和自己的原生庫(kù)關(guān)聯(lián) 參數(shù)1.原生庫(kù)的名稱(chēng) 2.預(yù)構(gòu)建庫(kù)的別名
target_link_libraries(native-lib ${log-lib} )
更加關(guān)于AS下的CMakeList.text內(nèi)容在Android的官方文檔里
三、在build.gradle里對(duì)CMake的一些必要配置
externalNativeBuild {
cmake {
path "CMakeLists.txt"http://指定CMakeLists.txt的路徑
}
}
四、在build.gradle里對(duì)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 {...}
}
}