A toy example to demostrate building an executable jar from a clojure file without a proper build tool. The process only depends on the Java tools java
and jar
being on the path. Both are included when installing the Java JDK. Tested on OS X.
Versions
Build with
./build.sh
Run with
java -jar build/hello.jar
To create an executable jar from a clojure source file we need to:
- Create a clojure source file with a main method
- Compile the file
- Merge the compiled class files with those in the clojure .jar into a new .jar file whose manifest's
Main-Class
points at the class generated for the clojure file
Create a file src/hello/core.clj
with (:gen-class)
in the ns
macro and a (defn -main ...)
function
(ns hello.Core
(:gen-class))
(defn -main [] (println "Hello, World!"))
Create a diretory into which the compiled classes will be placed.
mkdir -p classes
Compile the clojure file using compile. You'll need to add the root directory in which the clojure source file is (src
) to the classpath. The directory in which the compiled files will be placed (by default classes
) needs to be added as well.
java -classpath lib/clojure-1.8.0.jar:src:classes clojure.main -e "(compile 'hello.Core)"
At this point, the classes
directory should contain a hello
directory with several .class files in it.
Next, build a jar with the generated classes and those from clojure.jar. For ease, we'll just copy clojure.jar and then modify it.
mkdir -p build
cp lib/clojure-1.8.0.jar build/hello.jar
jar -ufe build/hello.jar hello.Core -C classes/ .
Finally, run the jar. It should print Hello, World!
java -jar build/hello.jar
- clojure enrty points: http://clojure.org/reference/repl_and_main
- clojure compilation: http://clojure.org/reference/compilation
jar
tool tutorial: http://docs.oracle.com/javase/tutorial/deployment/jar/index.html