背景

build.gradle.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
plugins {
kotlin("multiplatform")
}
group = "tech.eritquearcus"
version = 0.0.0.0
kotlin {
jvm {
compilations.all {
kotlinOptions.jvmTarget = "1.8"
}
withJava()
testRuns["test"].executionTask.configure {
useJUnitPlatform()
}
}
val hostOs = System.getProperty("os.name")
val isMingwX64 = hostOs.startsWith("Windows")
val nativeTarget = when {
hostOs == "Mac OS X" -> macosX64("unix")
hostOs == "Linux" -> linuxX64("unix")
isMingwX64 -> mingwX64("win")
else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
}
sourceSets {
val commonMain by getting {
dependencies {

}
apply(plugin = "org.jetbrains.kotlin.plugin.serialization")
}
val jvmMain by getting
val unixMain by getting
val winMain by getting
}
}

从代码里可以看出, 我是打算在 unixMainwinMain 下分别放 mac/linux 平台的实现, jvmMain 下放 java 实现.
但是在我单纯在这个项目的 src 根目录下新建 unixMainwinMain 后, 我发现他不会自己链接这两个文件夹(像 jvmMainnativeMain 一样), 然后报错:
file struct

1
2
3
4
5
6
7
8
9
10
11
12
13
14
KotlinSourceSet with name 'unixMain' not found.

* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Exception is:
org.gradle.api.UnknownDomainObjectException: KotlinSourceSet with name 'unixMain' not found.
at org.gradle.api.internal.DefaultNamedDomainObjectCollection.createNotFoundException(DefaultNamedDomainObjectCollection.java:504)
at org.gradle.api.internal.DefaultNamedDomainObjectCollection.getByName(DefaultNamedDomainObjectCollection.java:333)
at org.gradle.kotlin.dsl.NamedDomainObjectCollectionDelegateProvider.provideDelegate(NamedDomainObjectCollectionExtensions.kt:384)
at Build_gradle$1$2.execute(build.gradle.kts:53)
at Build_gradle$1$2.execute(build.gradle.kts:1)
...

解决方法

1
2
3
4
5
6
val unixMain = maybeCreate("unixMain").apply {
this.dependsOn(commonMain)
}
val winMain = maybeCreate("winMain").apply {
this.dependsOn(commonMain)
}

替换

1
2
val unixMain by getting
val winMain by getting