Gradle 插件深度配置
源:Kotlin Multiplatform Gradle DSL
Kotlin Multiplatform Gradle 插件提供了丰富的配置选项。本文深入讲解如何配置 Native 目标、优化构建、以及常用技巧。
基础配置
多目标配置
kotlin
// build.gradle.kts
kotlin {
// Android Native
androidNativeArm32()
androidNativeArm64()
androidNativeX86()
androidNativeX64()
// iOS
iosArm64()
iosX64()
iosSimulatorArm64()
// macOS
macosX64()
macosArm64()
// Linux
linuxX64()
linuxArm64()
// Windows
mingwX64()
}Source Sets 配置
kotlin
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
}
}
val nativeMain by creating {
dependsOn(commonMain)
}
val androidNativeMain by creating {
dependsOn(nativeMain)
}
val androidNativeArm64Main by getting {
dependsOn(androidNativeMain)
}
}
}编译器配置
编译选项
kotlin
kotlin {
targets.withType<KotlinNativeTarget> {
binaries.all {
// 优化级别
freeCompilerArgs += "-opt" // 或 "-opt-in"
// 调试信息
freeCompilerArgs += "-g"
// 禁用断言
freeCompilerArgs += "-Xdisable-phases=Devirtualization"
// 内存模型
freeCompilerArgs += "-Xbinary=memoryModel=experimental"
}
}
}Build Types 配置
kotlin
kotlin {
androidNativeArm64 {
binaries {
sharedLib("release") {
baseName = "mylib"
optimized = true
freeCompilerArgs += listOf("-opt", "-Xallocator=mimalloc")
}
sharedLib("debug") {
baseName = "mylib-debug"
debuggable = true
freeCompilerArgs += listOf("-g", "-Xg0")
}
}
}
}依赖管理
C Interop 依赖
kotlin
kotlin {
linuxX64 {
compilations.getByName("main") {
cinterops {
val sqlite by creating {
defFile("src/nativeInterop/cinterop/sqlite.def")
packageName("sqlite")
compilerOpts("-I/usr/include")
includeDirs("/usr/include")
}
val openssl by creating {
defFile("src/nativeInterop/cinterop/openssl.def")
}
}
}
}
}平台依赖
kotlin
kotlin {
sourceSets {
val linuxX64Main by getting {
dependencies {
implementation("org.example:linux-specific:1.0")
}
}
val mingwX64Main by getting {
dependencies {
implementation("org.example:windows-specific:1.0")
}
}
}
}任务配置
自定义构建任务
kotlin
tasks.register("buildAll Native") {
group = "build"
description = "Build all native targets"
dependsOn(
"linkReleaseSharedAndroidNativeArm64",
"linkReleaseSharedAndroidNativeX64"
)
}
tasks.register<Copy>("copyNativeLibs") {
from("build/bin")
into("../app/src/main/jniLibs")
}掌握 Gradle 配置是高效 Native 开发的关键。合理的配置能够显著提升构建速度和产物质量。