IFDEF conditional compilation and ocamlbuild


#1

Hello,

I am developing a program in Ocaml for my Programming class.This idea is to provide the students with various versions of the program, using more and more complex techniques.

I would like to design a common master, and then derive the various versions automatically using some conditional compilation facility.

I considered camlp4 IFDEF but it applies to complete expressions, only. Instead, I would like to add or remove cases in long lists of if ... then ... else if ....

Also, I am using ocamlbuild and I cannot find how to define IFDEF compilation tags in the compilation chain.

Is there any IFDEF-wizard in the community? :sunglasses:

Best regards,

Luc.


#2

See https://github.com/ocaml-community/cppo + https://jbuilder.readthedocs.io/en/latest/quick-start.html#using-cppo (for dune, since using plain ocamlbuild is “an old way of doing things”).


#3

Note there is also https://github.com/janestreet/ppx_optcomp for using only extension points (PPX)


#4

Excellent! Let me try as soon as possible. Luc.


#5

I confirm: just perfect. Thanks!

I have another question. Is it possible to use ocamlformat on the code equipped with #ifdef directives?

I was careful to use them in a structured way, so that formatting the code obtained by ignoring the directives makes sense.

Regards, Luc.


#6

From my experience ocamlformat is not perfect yet, but I would just try and check the results in your case.


#7

If you do conditional compilation via ppx, as ppx_optcomp does, then ocamlformat has a chance. With other approaches where the source file does not parse using the standard compiler, ocamlformat will not work.


#8

Dear JJB,

I use cppo for conditional compilation. I am not acquainted enough: does it use ppx underneath?

Anyway, I tried with a test file, and it failed.

$ opam exec ocamlformat -- --inplace --profile=janestreet --debug test.ml
ocamlformat: ignoring "test.ml" (syntax error)
File "test.ml", line 130, characters 1-5:
Error: Syntax error

where line 130 is #else.


#9

I don’t know cppo in any detail, but that error message makes me suspect
that it is not implemented as a ppx transformation.


#10

cppo is not built as a ppx. And is not compatible with tools such as ocamlformat.


#11

As I mentioned already there is ppx_optcomp, which should work with ocamlformat.