Ocaml and You

Start out with emerge ocaml. This will get you the language fully installed and the xemacs packages. You will want to install ocamlfind, which is also known as findlib. Install with emerge findlib. This is needed to install and use extension packages, such as Getopt.

To compile your program into a bytecode executable, run ocamlc myprog.ml. This makes an executable file that invokes the interpreter, ocamlrun, to execute the bytecodes. If you want a native version (doesn't require ocamlrun), use ocamlopt myprog.ml.

If you need thread support*, you need to use open Thread in your code and give the -thread option to the compiler. This will ensure that the compiler links in the thread safe version of the libraries. You will also need to add -custom threads.cma. But threads depends on the unix module; so, add unix before threads. Now you have ocamlc -thread -custom unix.cma threads.cma myprog.ml.

To get any real work done, you'll probably need to use the lexer/parser. Include open Genlex in your code. Add -pp camlp4o -I +camlp4 to the compile options. This tells the compiler to preparse the file with camlp4o. The -I tells it to include the camlp4 directory when searching for cma and cmo files.

If you're going to be writing any decently large sized program, you'll also want to use getopts. Getopts is a standard C library for parsing the input parameters sent to an executable. Run the following. Then take a look at sample.ml and the docs in docs/index.html.

make allopt
make install

(* Verify Getopt is installed by running ocaml. *)
#use "topfind";;
#list;; (* should show getopt *)
#require "Getopt";;

The final compile command looks like ocamlc -thread -custom unix.cma threads.cma getopt.cma -pp camlp4o -I +camlp4 -I getopt myprog.ml. If you want to compile to native code, use ocamlopt -thread -pp camlp4o -I +camlp4 -I getopt unix.cmxa threads.cmxa getopt.cmxa myprog.ml. According to the documentation you also need to add -cclib -lunix -cclib -lthreads to the ocamlc command line and -cclib -lunix -cclib -lthreadsnat -cclib -lpthread to the ocamlopt command line. However, I didn't find this to be necessary.

Threads in Ocaml cannot run on more than one processor. So you probably won't get much of a speed increase by using them. Also, for some reason, I found that if you print from within a thread, the output does not show up on the console if the main thread quits. I assume this means all threads are immediately terminated (at least by default) when the main program ends. If you put a delay in the main program, the output will appear on the console after the delay. However, you can make the output appear immediately by putting %! in your formatted string. This tells printf to flush immediately.