Tuesday, September 13, 2011

learning clojure: how to compile clojure source code

Currently I am learning clojure now, I focused on the book "The joy of Clojure", but actually I did not enjoy the joy of clojure so far. For me the book is still difficult. As the author mentioned, this book is not for beginner. Most of my time I have to refer on the Clojure API document. Today I want to share my experience on learning chapter 10.2.1, how to compile a clojure source code.

The source code is in page 212, listing 10.3, called DynaFrame.clj:

The author mentioned how to ompile the source code:
 You can compile this namespace by saving it in a directory joy/gui, located on the classpath, in a file named DynaFrame.clj and executing the function (compile 'joy.gui.DynaFrame) in a fresh REPL.

As a clojure beginner, I found it is described not detailed enough, it took me almost a night to figure out how to build it successfully.
After fixing different weird problems, finally I got it working. Here is what I found:

1. Be careful clojure version: at first I use clojure 1.0 to launch the REPL to compile it, but I got Exception to complain not found java.lang. Later I realize the problem is in ^{:static true}, you have to use clojure 1.2 to compile it; if you still want to use clojure 1.0, then use #^{:static true} instead.

2. Use cljr tool, I found it is really handy to add classpath: just run cljr add-classpath <your folder>; run cljr list-classpath will display your classpath.

3. Add source code folder in the classpath
   put DynaFrame.clj under joy/gui, and
   run cljr add-classpath ./

4. Add *compile-path*
   create an directory called "classes", and
   run cljr add-classpath classes/
   Based on the clojure API document:*compile-path* defaults to "classes", the directory must be in the classpath for 'compile' to work.

5. run cljr repl to launch the REPL,  type
    (compile 'joy.gui.DynaFrame)
   and
    (joy.gui.DynaFrame. "1st")

In summary, to compile the clojure code successfully, you need:
 - Add source folder in the classpath;
 - Create and add "classes" folder in the classpath


No comments:

Post a Comment