Tutorial: ocamlc


The ocamlc tool compiles your Ocaml source files into a binary executable. This is similar to using gcc or javac. Given an *.ml file, ocamlc will compile and produce an executable. It will produce a file called a.out (just like gcc) by default. A different program name can be specified by using the "-o <file>" option. You can also use -g flag to turn on debugging information. Executables with debugging information can be used in another Ocaml tool, ocamldebug. The other files created include *.cmi which are interface files and *.cmo which are the object files (like *.o in C).

Once you have the executable created by ocamlc, you can run it with ocamlrun (like java). Most of the time though, the executables will run directly from your shell prompt like any other program. Sometimes you may need to pass arguments to your program. Command line arguments can be accessed in Ocaml by the Sys.argv.(n) command where n is the argument number.

A simple factorial example is provided below for using the options discussed above.

Common options you might use for ocamlc:

canopus:~/ta/505/examples/fact> ocamlc --help
Usage: ocamlc <options> <files>
Options are:
-a Build a library
-c Compile only (do not link)
-cc <command> Use <command> as the C compiler and linker
-cclib <opt> Pass option <opt> to the C linker
-ccopt <opt> Pass option <opt> to the C compiler and linker
-g Save debugging information
-i Print the types
-I <dir> Add <dir> to the list of include directories
-impl <file> Compile <file> as a .ml file
-o <file> Set output file name to <file>
-output-obj Output a C object file instead of an executable
-help display this list of options
--help display this list of options ...

Factorial source (download):

(* Factorial Program *)


(* Define the factorial function *)
let rec fact(n) =
  if(n=0) then 1
  else n * fact(n-1);;


(* Get the argument with Sys.argv *)
let n = int_of_string Sys.argv.(1);;


(* When using ocamlc, the output you see when
   executing statements in the interpreter (ocaml)
   are not printed to the console, so you must
   manually call a print function to print
   your output.
*)
print_string("Factorial of ");;
print_int(n);;
print_string(" is ");;
print_int(fact (n));;
print_string("\n");;

Factorial output:

canopus:~/ta/505/examples/fact> ocamlc -g -o fact fact.ml
canopus:~/ta/505/examples/fact> ls
fact fact.cmi fact.cmo fact.ml canopus:~/ta/505/examples/fact> ./fact 4
Factorial of 4 is 24