Question

I have found many guides on how to build .o files from C sources using ocamlbuild. These do not apply to C++ files, however, which ocamlbuild cannot build out of the box.

I have tried writing a myocamlbuild.ml file (shown below after request) providing a rule from .cpp to .o and that fails with ocamlc complaining that it does not know what to do with a .cpp file (even when the compiler is set to g++ via command line flags).

open Ocamlbuild_plugin ;;

let ext_obj = !Options.ext_obj;;
let x_o = "%"-.-ext_obj;;

rule "ocaml C++ stubs: cpp -> o"
  ~prod:x_o
  ~dep:"%.cpp"
  begin fun env _build ->
    let c = env "%.cpp" in
    let o = env x_o in
    let comp = 
      if Tags.mem "native" (tags_of_pathname c) then !Options.ocamlopt else !Options.ocamlc in
    let cc = 
      Cmd(S[comp; T(tags_of_pathname c++"c"++"compile"); A"-custom"; A"-cc"; A"g++"; A"-c"; Px c]) in
    if Pathname.dirname o = Pathname.current_dir_name then cc
    else Seq[cc; mv (Pathname.basename o) o]
  end;;

The file libsoundness.clib consists of a bunch of .o files.

When I do ocamlbuild libsoundness.a I get the following output:

Finished, 0 targets (0 cached) in 00:00:00.
+ /usr/bin/ocamlc.opt -custom -cc g++ -c src/soundness/proof_aut.cpp
/usr/bin/ocamlc.opt: don't know what to do with src/soundness/proof_aut.cpp.
Usage: ocamlc <options> <files>
<snipped long list of ocamlc options>

The only other solution for C++ seems to be ocamlbuild-ctools whose website is defunct (I could not download any sources).

Any ideas?

Was it helpful?

Solution

cf. my answer to the similar question.

I recommend the following approach :

  1. name c++ files with .c extension so that ocamlc picks them up
  2. tell gcc that those are actually c++ files with -x c++
  3. tell ocamlbuild that the build actually depends on .h files (e.g. list .h files together with .c in the CSources field in _oasis)
  4. do not forget to link -lstdc++ explicitely cause gcc will not do that being a C compiler it is
  5. use cxx_wrapped.h to get that real C++ feel
  6. PROFIT!!

See hypertable bindings as an example of this approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top