开发者

Is it possible to compile clojure source without going into REPL?

开发者 https://www.devze.com 2023-04-12 11:54 出处:网络
Is it possible to compile clojure source without going into REPL? If a big project is there then it is not possible to compile each program manually & then make jar file of it, like if i wish to 开

Is it possible to compile clojure source without going into REPL? If a big project is there then it is not possible to compile each program manually & then make jar file of it, like if i wish to 开发者_C百科compile and get class files by some set of instructions in make software?


For the sake of understanding how many of these systems work underneath, here is some bare minimum code to compile code without a repl.

Say you have some class generating code:

hello.clj:

 (ns hello
   (:gen-class
    :methods [[sayHi [] String]]))

 (defn -sayHi [this]
   (println "hello world"))

You can build your "makefile" out of clojure code

compile.clj:

 (set! *compile-path* "./")
 (compile 'hello)

Then you just call your code as a script.

 $ java -cp ~/dj/lib/clojure.jar:./ clojure.main compile.clj 
 $ ls
 compile.clj  hello.clj          hello$loading__4505__auto__.class
 hello.class  hello__init.class  hello$_sayHi.class

Now your code is compiled and you can access it like any other class file:

 $ java -cp ~/dj/lib/clojure.jar:./ clojure.main
 Clojure 1.3.0
 user=> (import 'hello)
 hello
 user=> (.sayHi (hello.))
 "hello world"
 user=> 


Yes - you can certainly compile and run Clojure code without using a REPL.

Some options to do this:

  • Load the Clojure code at runtime using the load function. This will read, compile and evaluate the Clojure code specified without any REPL involved.
  • Package everything as a .jar using Leiningen or Maven or any other suitable build tool - then you can run your code as a regular Java application, the Clojure code will be compiled and run when the .jar is executed
  • Launch the code from Java - write a Java application that launches the Clojure compiler directly to compile and then execute the Clojure code. This might be a sensible approach if you are using Clojure as a component of a larger Java application.


I have a large project using many languages and use make as the glue to start all the other components and this works quite well. You may do well to have make call maven or leiningen instead of using make to reinvent them.

If you are looking for an alternative to leiningen because it is not working for you or you simply wish to use something else, then perhaps you will like the Clojure Maven plugin

Personally I can't speak too highly of Leiningen and it is my personal choice, though there are many people in the internet and it's worth exploring the other options.

0

精彩评论

暂无评论...
验证码 换一张
取 消