Kotlin cross-compilation for multiple targets in single build run

Viewed 174

Default Kotlin native project gradle configuration looks like:

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
    }
}

Such configuration can produce binaries only for single target. How can be the configuration adjusted so that single build will produce 3 binary for all mentioned targets: Windows, Linux and MacOS?

1 Answers

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)
        }
    }
}
Related