kotlin program error: no main manifest attribute in jar file

I came accross this answer while having the same issue with Kotlin and gradle. I wanted to package to get the jar to work but kept on pilling errors.

With a file like com.example.helloworld.kt containing your code:

fun main(args: Array<String>) {
    println("Hello, World!")
}

So here is what the file build.gradle.kts would look like to get you started with gradle.

import org.gradle.kotlin.dsl.*
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
  application
  kotlin("jvm") version "1.3.50"
}

// Notice the "Kt" in the end, meaning the main is not in the class
application.mainClassName = "com.example.MainKt"

dependencies {
  compile(kotlin("stdlib-jdk8"))
}

tasks.withType<KotlinCompile> {
  kotlinOptions.jvmTarget = "1.8"
}

tasks.withType<Jar> {
    // Otherwise you'll get a "No main manifest attribute" error
    manifest {
        attributes["Main-Class"] = "com.example.MainKt"
    }
    
    // To avoid the duplicate handling strategy error
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE

    // To add all of the dependencies otherwise a "NoClassDefFoundError" error
    from(sourceSets.main.get().output)

    dependsOn(configurations.runtimeClasspath)
    from({
        configurations.runtimeClasspath.get().filter { it.name.endsWith("jar") }.map { zipTree(it) }
    })
}

So once you gradle clean build you can either do:

gradle run
> Hello, World!

Assuming your projector using the jar in build/libs/hello.jar assuming that in your settings.gradle.kts you have set rootProject.name = "hello"

Then you can run:

java -jar hello.jar
> Hello, World!

Leave a Comment