一埂息、什么是CMake
或許聽過好幾種 Make 工具皮璧,如 GNU Make 舟扎,qmake,MS nmake等悴务。這些 Make 工具遵循著不同的規(guī)范和標準睹限,所執(zhí)行的 Makefile 格式也千差萬別。如果軟件想跨平臺讯檐,必須要保證能夠在不同平臺編譯羡疗。而如果使用上面的 Make 工具,就得為每一種標準寫一次 Makefile 别洪。
CMake就是針對上面問題所設(shè)計的工具叨恨,它讓開發(fā)者編寫一種平臺無關(guān)的 CMakeList.txt 文件來定制整個編譯流程,然后再根據(jù)目標用戶的平臺進一步生成所需的本地化 Makefile 和工程文件挖垛。
二痒钝、CMakeList.txt文件
如上所述,這個文件是用來定制編譯流程的晕换。里面包含的是一些命令午乓。
CMakeLists.txt 的語法比較簡單,由命令闸准、注釋和空格組成益愈,其中命令是不區(qū)分大小寫的。符號 # 后面的內(nèi)容被認為是注釋。命令由命令名稱蒸其、小括號和參數(shù)組成敏释,參數(shù)之間使用空格進行間隔。
如下是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)
#添加庫或者源文件,參數(shù)1.生成庫的名字 2.生成庫的類型 3.源文件所在路徑
add_library(native-lib SHARED src/main/cpp/native-lib.cpp )
#查找NDK提供的庫靠汁,這里是查找用于打印日志的log庫蜂大,參數(shù)1.給查找?guī)斓膭e名 2.查找?guī)斓拿Q
find_library(log-lib log )
#將預(yù)構(gòu)建的庫和自己的原生庫關(guān)聯(lián) 參數(shù)1.原生庫的名稱 2.預(yù)構(gòu)建庫的別名
target_link_libraries(native-lib ${log-lib} )
更加關(guān)于AS下的CMakeList.text內(nèi)容在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 {...}
}
}