首页 > 解决方案 > 单次构建运行中多个目标的 Kotlin 交叉编译

问题描述

默认 Kotlin 原生项目 gradle 配置如下所示:

plugins {
    kotlin("multiplatform") version "1.4.10"
}
group = "org.example"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}
kotlin {
    val hostOs = System.getProperty("os.name")
    val isMingwX64 = hostOs.startsWith("Windows")
    val nativeTarget = when {
        hostOs == "Mac OS X" -> macosX64("native")
        hostOs == "Linux" -> linuxX64("native")
        isMingwX64 -> mingwX64("native")
        else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
    }

    nativeTarget.apply {
        binaries {
            executable {
                entryPoint = "main"
            }
        }
    }
    sourceSets {
        val nativeMain by getting
        val nativeTest by getting
    }
}

这种配置只能为单个目标生成二进制文件。如何调整配置,以便单个构建将为所有提到的目标生成 3 个二进制文件:Windows、Linux 和 MacOS?

标签: kotlincross-compilingkotlin-native

解决方案


You can just set a number of targets, and then running the assemble task will produce binaries for all available on your host machine. It is important because one cannot create a binary for macOS anywhere but on macOS host, Windows target also has some complex preparations(see this issue). Also, there could be some problem with source sets - if their contents are identical, maybe it worth connecting them as in the example below:

kotlin {
    macosX64("nativeMac")
    linuxX64("nativeLin")
    mingwX64("nativeWin")

     targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
        binaries {
            executable {
                entryPoint = "main"
            }
        }
    }

    sourceSets {
        val nativeMacMain by getting //let's assume that you work on Mac and so put all the code here
        val nativeLinMain by getting {
            dependsOn(nativeMacMain)
        }
    }
}

推荐阅读