Simple Example where Ocaml calls a C function

While there a great deal of techniques and ressources that help to connect Ocaml with C, I had hard time to find a very simple example that shows how you can call a C function from Ocaml.

This example shows a foreign function call via Ocamls FFI (Foreign Function Interface). Based on a question on StackOverflow.com In OCaml 4.03.0 FFI fails to compile with “No implementations provided” Error.

Sources

Makefile

.PHONY: all clean 

all: main
    ./main

main:
    ocamlopt -c hello_stubs.c
    ocamlopt -o main main.ml hello_stubs.o

clean:
    rm -f main
    rm -f *.o
    rm -f *.cm*
    

main.ml

external print_hello : unit -> unit = "caml_print_hello"

let _ = print_hello();;

hello_stubs.c

#include<stdio.h>
#include<caml/mlvalues.h>
CAMLprim value caml_print_hello(value unit)
{
    printf("Hello\n");
    return Val_unit;
}

Downloads

basic-ocaml-ffi_20240828121852.zip