18.10 Building mixed C/Caml libraries: ocamlmklib

The ocamlmklib command facilitates the construction of libraries containing both Caml code and C code, and usable both in static linking and dynamic linking modes.

Windows:

This command is available only under Cygwin, but not for the native Win32 port.

The ocamlmklib command takes three kinds of arguments:

It generates the following outputs:

C object files.

In addition, the following options are recognized:

Example

Consider a Caml interface to the standard libz C library for reading and writing compressed files. Assume this library resides in /usr/local/zlib. This interface is composed of a Caml part zip.cmo/zip.cmx and a C part zipstubs.o containing the stub code around the libz entry points. The following command builds the Caml libraries zip.cma and zip.cmxa, as well as the companion C libraries dllzip.so and libzip.a:

ocamlmklib -o zip zip.cmo zip.cmx zipstubs.o -lz -L/usr/local/zlib

If shared libraries are supported, this performs the following commands:

ocamlc -a -o zip.cma zip.cmo -dllib -lzip \
        -cclib -lzip -cclib -lz -ccopt -L/usr/local/zlib
ocamlopt -a -o zip.cmxa zip.cmx -cclib -lzip \
        -cclib -lzip -cclib -lz -ccopt -L/usr/local/zlib
gcc -shared -o dllzip.so zipstubs.o -lz -L/usr/local/zlib
ar rc libzip.a zipstubs.o

If shared libraries are not supported, the following commands are performed instead:

ocamlc -a -custom -o zip.cma zip.cmo -cclib -lzip \
        -cclib -lz -ccopt -L/usr/local/zlib
ocamlopt -a -o zip.cmxa zip.cmx -lzip \
        -cclib -lz -ccopt -L/usr/local/zlib
ar rc libzip.a zipstubs.o

Instead of building simultaneously the bytecode library, the native-code library and the C libraries, ocamlmklib can be called three times to build each separately. Thus,

ocamlmklib -o zip zip.cmo -lz -L/usr/local/zlib
    

builds the bytecode library zip.cma, and

ocamlmklib -o zip zip.cmx -lz -L/usr/local/zlib
    

builds the native-code library zip.cmxa, and

ocamlmklib -o zip zipstubs.o -lz -L/usr/local/zlib

builds the C libraries dllzip.so and libzip.a. Notice that the support libraries (-lz) and the corresponding options (-L/usr/local/zlib) must be given on all three invocations of ocamlmklib, because they are needed at different times depending on whether shared libraries are supported.