I'm trying to call some ocaml code from a C program. I've been following some of the documentation here. The c program is called hello.c
, and it is attempting to use Ocaml functions defined in callme.ml
.
As in the link, I'm doing this in two steps: first compile the ml file to an object file:
ocamlopt -output-obj -o callme2.o callme.ml
And then attempt to link it to my 'main' binary with this code:
gcc -Wall -I`ocamlopt -where` -L`ocamlopt -where` -lasmrun -lm -ldl -o hello hello.c callme2.o -lasmrun
But I run into the following problem: main
is already defined in libasmrun.a, and so it conflicts with the main
in my own hello.c
:
/tmp/ccANhYNH.o: In function `main':
hello.c:(.text+0x58): multiple definition of `main'
/home/orm/.opam/4.02.0/lib/ocaml/libasmrun.a(main.o):main.c:(.text+0x0): first defined here
How can I work around this? (As the library path suggests, I'm using ocaml version 4.02)
update: this problem has more to do with proper usage of C linker flags, rather than ocaml. Using the flags in the following order fixes the problem:
gcc -Wall -I`ocamlopt -where` -L`ocamlopt -where` -o hello hello.c -lasmrun callme2.o -lm -ldl -lasmrun
This is interesting, because I thought it was illegal to have the same function name defined twice in the same program. Maybe this is one of the exceptions in that document.
Your command line is a little strange, as
-lasmrun
shows up twice.Here's something that has worked for me:
You can see a working example in my pseudo-blog: Further OCaml GC Disharmony.
(As I learned the hard way, make sure you follow the rules of GC harmony :-)