【KMP】解决桌面端打包异常无法运行

最近用kotlin compose desktop搓了个PC端小工具,发现个怪事,必须用IDEA才能运行,打包成EXE就点不开,一点反应都没有,也没有报错。

最后发现是因为mainClass的配置有问题导致的。

在最外层的build.gradle.kts里有这么一段:

ini 复制代码
compose.desktop {
    application {
        mainClass = "MainKt"  <----就是它

        nativeDistributions {
            targetFormats(TargetFormat.Dmg, TargetFormat.Exe, TargetFormat.Deb)
            packageName = "ApkManager"
            packageVersion = "1.0.0"
        }
    }
}

这里的mainClass是主程序文件的名字,后面那个Kt是后缀(对没错那是后缀)

在项目一开始创建的时候,默认在kotlin目录下生成了一个Main.kt文件,所以这里默认就写了mainClass = "MainKt",其实就是去掉后缀名的点,然后用驼峰命名。

后来我改过这个Main.kt文件,给它加了包名,于是运行的时候就找不到了,离谱的是找不到竟然不报错。

解决办法非常简单,在前面加上包名就可以了。

ini 复制代码
compose.desktop {
    application {
        mainClass = "com.dubhe.apkmamanger.MainKt"

        nativeDistributions {
            targetFormats(TargetFormat.Dmg, TargetFormat.Exe, TargetFormat.Deb)
            packageName = "ApkManager"
            packageVersion = "1.0.0"
        }
    }
}

如果文件名有多个隔断,前面的用下划线替代,最后的直接去掉。像这样:

原文件名:main.desktop.kt

ini 复制代码
compose.desktop {
    application {
        mainClass = "Main_desktopKt"
    }
}

虽然这个参数的名字叫mainClass,但实际上那个目标文件如果不是Class,直接把main函数扔外面也是可以的。但是main函数是一定要有的。

如果觉得很麻烦建议直接不要动这个主入口文件,new出来长啥样就啥样,逻辑全写另一个类里引用它就好。免得抽风。

相关推荐
ULTRA??20 小时前
归并排序算法实现,kotlin,c++,python
c++·python·kotlin
Kapaseker1 天前
四大组件齐上阵,轻松拿捏实习生
android·kotlin
Kapaseker2 天前
三分钟搞懂 Kotlin Flow 中的背压
android·kotlin
QING6182 天前
Jetpack Compose 中的 ViewModel 作用域管理 —— 新手指南
android·kotlin·android jetpack
KotlinKUG贵州3 天前
Kotlin/Ktor 实践:利用 MCP 从零打造 AI Agent 服务端指南
kotlin·agent·mcp
喜熊的Btm3 天前
探索 Kotlin 的不可变集合库
kotlin·android jetpack
モンキー・D・小菜鸡儿4 天前
Android 中 StateFlow 的使用
android·kotlin
我又来搬代码了4 天前
【Android】【Compose】Compose知识点复习(一)
android·前端·kotlin·android studio
hnlgzb4 天前
好像kotlin class和kotlin file都可以是activity?
android·开发语言·kotlin