Version française
Home     About     Download     Resources     Contact us    
Browse thread
linking errors involving cpp files
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Aaron Bohannon <bohannon@c...>
Subject: linking errors involving cpp files
Hi,

How do I link C++ code with OCaml?  Let's say I have a main program in
C/C++ and a function I want to call in OCaml:

---- main.c / main.cpp ---
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/callback.h>
int main (int argc, char ** argv) {
  char * caml_argv[argc + 1];
  int i;
  for (i = 0; i < argc + 1; i++) caml_argv[i] = argv[i];
  caml_argv[argc] = NULL;
  caml_main (caml_argv);
  return 0;
}
--------

---- test.ml ----
let f x = x + 1
let () = Callback.register "test" f
--------

If I name the main program "main.c", I can compile the code like this
with no trouble whatsoever:

gcc -I /opt/local/lib/ocaml -c main.c
ocamlopt -o main test.cmx main.o

If I name the main program "main.cpp", and run the same commands---

gcc -I /opt/local/lib/ocaml -c main.cpp
ocamlopt -o main test.cmx main.o

---then I get this:

Undefined symbols:
  "_caml_atom_table", referenced from:
      _intern_alloc in libasmrun.a(intern.o)
      _intern_rec in libasmrun.a(intern.o)
      _caml_alloc in libasmrun.a(alloc.o)
      _caml_alloc_dummy_float in libasmrun.a(alloc.o)
      _caml_alloc_dummy in libasmrun.a(alloc.o)
      _caml_alloc_array in libasmrun.a(alloc.o)
  "___gxx_personality_v0", referenced from:
      _main in main.o
      CIE in main.o
  "_caml_code_area_start", referenced from:
      _extern_rec in libasmrun.a(extern.o)
      _extern_rec in libasmrun.a(extern.o)
      _segv_handler in libasmrun.a(signals_asm.o)
      _caml_code_checksum in libasmrun.a(intern.o)
      _intern_rec in libasmrun.a(intern.o)
  "_caml_code_area_end", referenced from:
      _extern_rec in libasmrun.a(extern.o)
      _segv_handler in libasmrun.a(signals_asm.o)
      _caml_code_checksum in libasmrun.a(intern.o)
  "caml_main(char**)", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
File "caml_startup", line 1, characters 0-1:
Error: Error during linking


Now I know gcc does something slightly different with cpp files, and I
can eliminate the complaint about the __gxx symbol if I add "-cclib
-lstdc++" (which I fully expected to need working with C++ programs).
But why are the caml symbols missing!?!?  (It took me over 2 hours to
figure out it was the "cpp" extension that was the root of these
missing caml symbols in my real program because that was the *last*
thing I expected.)  I'm using OCaml 3.11.1 on OS X 10.6.2.

- Aaron