#include <caml/mlvalues.h>
#include <caml/callback.h>
void hello() {
static value *closure = NULL;
if(!closure) closure = caml_named_value("hello");
caml_callback(*closure, Val_unit);
}
int main(int argc, char **argv) {
caml_main(argv);
hello();
return 0;
}
And the following "hello.ml":
let hello () = print_endline "Hello, world!"
let () = Callback.register "hello" hello
I can then compile as follows on OS X 10.5:
ocamlopt -c hello.ml -o hello.cmx
ocamlopt -output-obj hello.cmx -o hello.o
gcc -c main.c -o main.o -I"`ocamlc -where`"
gcc -o hello hello.o main.o -L"`ocamlc -where`" -ldl -lm -lasmrun
This works fine on OS X. However, it does not seem to work on Linux/
AMD64 or FreeBSD/AMD64. I've tried suggestions from all over the web
and I've tried the approach given in the manual and nothing works. In
all non-Mac cases, I get this on the second line:
hello.o: file not recognized: File truncated
Error during linking
One thing I can do is do this instead of the first two lines:
ocamlopt -c -output-obj hello.ml
However, then I get the following:
hello.o: In function `camlHello__hello_58':
(.text+0x8): undefined reference to
`camlPervasives__print_endline_298'
/usr/lib/ocaml/3.10.2/libasmrun.a(startup.o): In function
`caml_main':
(.text+0x25f): undefined reference to `caml_data_segments'
/usr/lib/ocaml/3.10.2/libasmrun.a(startup.o): In function
`caml_main':
(.text+0x273): undefined reference to `caml_code_segments'
...
Does anyone have a correct set of instructions for doing this on non-
Mac platforms? Thanks.
- John
_______________________________________________
Caml-list mailing list. Subscription management:
http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
Archives: http://caml.inria.fr
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs
This is the main problem. You're clobbering the hello.o that OCaml
produced when compiling hello.ml into native code.
> Does anyone have a correct set of instructions for doing this on
> non-Mac platforms? Thanks.
This worked fine for me:
ocamlopt -output-obj -o temp.o hello.ml
gcc -o hello main.c temp.o -L/usr/lib/ocaml -lasmrun -lm -ldl
> On Sun, Nov 15, 2009 at 08:27:49AM -0500, John Nowak wrote:
>
>> I'm trying to call OCaml from C.
>> [...]
>> ocamlopt -output-obj hello.cmx -o hello.o
>
> This is the main problem. You're clobbering the hello.o that OCaml
> produced when compiling hello.ml into native code.
Works well now, thanks. Perhaps the documentation could be amended to
make this more clear. Although, in retrospect, I should've realized
what was happening.
- John