如何为 iOSArm64 与 macOSArm64 分别设置不同的编译标志?
解读
在国内 Android→KMM→iOS 的跨平台链路里,“一套源码、两套产物” 是常态。面试官问的不是“会不会写 compilerArgs”,而是考察候选人能否在 Gradle 配置阶段 就精确区分 iOSArm64 与 macOSArm64 这两个 Kotlin/Native target,并保证:
- 不侵入共享源码;
- 不与 CI 上的 x86_64 产物冲突;
- 支持增量缓存与远程缓存,不触发全量重链;
- 遵守国内苹果上架合规要求(bitcode、签名、隐私清单)。
一句话:既要 “区分得开”,又要 “缓存得住”,还要 “发得上架”。
知识点
- Kotlin/Native 双维度模型:
Target(预设的 iosArm64、macosArm64)Compilation(MAIN、TEST)Binary(FRAMEWORK、DYNAMIC、STATIC)
三者共同决定最终 clang 参数入口。
- compilerOptions DSL(Kotlin 1.9+)与 deprecated 的
compilations.all { kotlinOptions {} }的区别。 - Gradle Configuration Cache 对
target.compilations.matching { }的兼容规则:任何project.afterEvaluate里动态添加的 freeCompilerArgs 都会使缓存 miss。 - 国内 CI 镜像源(阿里云、腾讯云)对 Kotlin/Native 依赖的 Konan 工具链 缓存路径
~/.konan的并发读写问题。 - Xcode 15 默认启用 bitcode=NO,但企业包仍需手动关闭,否则上传 App Store Connect 会报 “Invalid Bundle”。
答案
在 kotlin 块内使用 per-target DSL,保证在 配置阶段 就完成区分,避免 afterEvaluate 导致缓存失效:
kotlin {
// 1. 注册 target
iosArm64("ios") {
// 2. 仅对 MAIN compilation 追加 iOS 专用标志
compilations.getByName(KotlinCompilation.MAIN_COMPILATION_NAME) {
compilerOptions.configure {
// 国内上架必须关闭 bitcode
freeCompilerArgs.addAll(
"-Xbinary=bitcode=disable",
"-Xruntime-logs=gc=info"
)
}
}
}
macosArm64("macos") {
compilations.getByName(KotlinCompilation.MAIN_COMPILATION_NAME) {
compilerOptions.configure {
// macOS App 不需要 bitcode,但需要签名标识
freeCompilerArgs.addAll(
"-Xbinary=memoryModel=experimental",
"-Xadd-light-debug=enable"
)
}
}
}
// 3. 共享源码集合
sourceSets {
val commonMain by getting
val iosMain by getting { dependsOn(commonMain) }
val macosMain by getting { dependsOn(commonMain) }
}
}
要点说明
- 未使用
all { }或afterEvaluate { },因此 Configuration Cache 可安全命中。 - 每个 target 仅改动自己的
KotlinCompilation,不会污染 其他架构。 - 若 CI 需额外注入版本号,可通过
gradle.properties读取,禁止 在freeCompilerArgs.add("-DMY_VER=${project.version}")中直接引用project,应改用providers.gradleProperty("my.ver").get()以兼容 Configuration Cache。
拓展思考
- 如果未来加入 iosSimulatorArm64,如何复用 iosArm64 的编译参数?
答:在targets.withType<KotlinNativeTarget>()循环里,用target.konanTarget.name做 when 分支,将公共 iOS 参数抽成val iosFlags = listOf(...),再分别addAll,既保证 DRY,又避免重复配置导致缓存碎片。 - 国内合规要求 隐私清单 PrivacyInfo.xcprivacy 如何与 Gradle 集成?
答:在linkTask的doLast里,用executedAssembleTask的outputFile定位.framework目录,再把仓库根目录的PrivacyInfo.xcprivacy拷贝 进Resources,注意 必须 在doLast而非doFirst,否则增量构建会跳过。 - 远程构建缓存场景下,如何验证 iOSArm64 与 macOSArm64 的缓存 key 不会冲突?
答:执行./gradlew :shared:printCompileTaskGraph -Pkotlin.native.cacheKind=static观察 task path 已天然带 target 名(compileKotlinIosArm64vscompileKotlinMacosArm64),且 Konan 版本 与 freeCompilerArgs 已作为输入,缓存 key 自动隔离;若仍冲突,可自定义gradle.remote.build.cache.key.prefix=$HOSTNAME以物理隔离。