Previous Contents Next

Main program in C

Until now, the entry point of our programs was in Objective CAML; the program could then call C functions. Nothing prevents us from writing the entry point in C, and having the C code call Objective CAML functions when desired. To do this, the program must define the usual C main function. This function will then initialize the Objective CAML runtime system by calling the function caml_main(char **), which takes as an argument the array of command-line arguments that corresponds to the Sys.argv array in Objective CAML. Control is then passed to the Objective CAML code using callbacks (see page ??).

Linking Objective CAML code with C

The Objective CAML compiler can output C object files (with extension .o) instead of Objective CAML object files (with extension .cmo or .cmx). All we need to do is set the -output-obj compiler flag.
ocamlc -output-obj files.ml
ocamlopt -output-obj.cmxa files.ml
From the Objective CAML source files, an object file with default name camlprog.o is produced.

The final executable is obtained by linking, using the C compiler, and adding the library -lcamlrun if the Objective CAML code was compiled to bytecode, or the library -lasmrun if it was compiled to native code.
cc camlprog.o filesC.o -lcamlrun 
cc camlprog.o filesC.o -lasmrun
Calling Objective CAML functions from the C program is performed as described previously, via the callback functions. The only difference is that the initialization of the Objective CAML runtime system is performed via the function caml_startup instead of caml_main.






Previous Contents Next