2017-01-21: Creating Self-Contained Jar Files for Kawa Scheme Programs

Kawa Scheme runs Scheme programs on the JVM. This post explores how to compile and pack up a Scheme program into a self-contained Jar file, along with the Kawa environment, for effortless distribution to users.

Example program

The following Kawa program displays a simple JFrame with a message, and exits when the close button is clicked:

;; Display a simple frame with a message, using Kawa Scheme

(import (scheme base)
        (class javax.swing JFrame JLabel))

(define frame (JFrame:new "Example"))
(invoke frame 'setDefaultCloseOperation JFrame:EXIT_ON_CLOSE)
(invoke frame 'setSize 300 200)
(invoke frame 'add (JLabel:new "Hello from Kawa"))
(invoke frame 'setVisible #t)

Saved in a file "swing.sps", the program is run using the command:

    > kawa swing.sps

Compiling to class files

Kawa uses the -C switch for compiling to a class. The --main switch is needed to identify the file as containing the main method, which Java uses to start your program.

    > kawa --main -C swing.sps 
    (compiling swing.sps to swing)
    > ls -l
    total 8
    -rw-rw-r-- 1 peter peter 1501 Jan 21 19:16 swing.class
    -rw-rw-r-- 1 peter peter  340 Jan 21 19:12 swing.sps
    > java -cp .:$KAWA_PATH/lib/kawa.jar swing

The last line above illustrates how to run the program. Note how the classpath is provided: we need our current folder (with our compiled classes) as well as Kawa itself.

Packing into a jar

The following three steps create a self-contained jar file.

First, unpack +kawa.jar+ into its own folder, kawa:

    > mkdir kawa
    > cd kawa
    > jar xf $KAWA_PATH/lib/kawa.jar 
    > cd ..

Second, we need a file letting Java know where to find the main method. The implicit class created by Kawa to hold our program is the same as our filename. In this case, create a simple manifest file called "swing.mf" containing:

    Main-Class: swing

Third, package all the files into a jar file:

    > jar cfm swing.jar swing.mf swing.class -C kawa .

The final jar file is now a self-contained java application. For this example, it is around 3.3MB in size.

Page from Peter's Scrapbook, output from a VimWiki on 2024-01-29.