3
votes

I'm trying to compile clojure source into class file, and run it using command line only, no lein, nor (possibly) reply.

I have core.clj in src/hello directory.

.
└── src
    └── hello
        └── core.clj

This is source code.

(ns hello.core)
(defn -main
  "This should be pretty simple."
  []
  (println "Hello, World!"))

using (compile) in REPL.

From the hint in this site (http://clojure.org/compilation), I tried to get class file from REPL.

I started REPL with lein repl in src directory, then tried to compile to get an error.

user=> (compile 'hello.core)

CompilerException java.io.IOException: No such file or directory, compiling:(hello/core.clj:1:1)  

Command line

From this post simple tool for compiling Clojure .clj into .class / .jar and How to compile file in clojure, it seems like that I can compile the clojure source outside REPL.

I tried this in . to get an error.

> java -cp .:<PATH>/clojure-1.6.0.jar -Dclojure.compile.path=build clojure.lang.Compile src/hello/core.clj 
Compiling src/hello/core.clj to build
Exception in thread "main" java.io.FileNotFoundException: Could not locate 
hello/core/clj__init.class or hello/core/clj.clj on classpath: 
at clojure.lang.RT.load(RT.java:443)
at clojure.lang.RT.load(RT.java:411) 
...

So, here are my questions:

  • How can I compile the clojure source to get the class with/without REPL?
  • How to run the class with Java? Is it enough to execute java -cp .:CLOJURE_JAR main?
1
and where does gradle join the party?cfrick
@cfrick: I updated the title.prosseek

1 Answers

3
votes

REPL

When invoking REPL, you should add class path.

java -cp .:<PATH>/clojure-1.6.0.jar:./src clojure.main

You need to set the *compile-path* with (set! *compile-path* "build").

Then you can compile to get the class file.

user=> (compile 'hello.core)
hello.core

Command line

There are two issues:

  1. For compilation, the CP should include the source directory.
  2. The parameter is not the file path, but the namespace.

This is to invoke the compiler.

clojure> java -cp .:<PATH>/clojure-1.6.0.jar:./src -Dclojure.compile.path=build clojure.lang.Compile hello.core
Compiling hello.core to build

Execution of the class file

You should point to the directory where the class files are located.

clojure> java -cp .:<PATH>/clojure-1.6.0.jar:./build hello.core
Hello, World!

References