Conditional libraries with dune and cppo

Hi everyone,

I have a library that I’d really like to have some form of conditional compilation for, and I’m not entirely sure how to get dune to handle this. The rough setup is as follows:

  1. We have a set of backends that all build their own libraries (wrappers to C mainly)
  2. Inside the main library we have modules that call into these libraries as required + code for selection etc

However, in practice we often don’t want all the backends available with the library so it would be great to be able to create a lightweight/full variant.

What I wanted to do was use cppo to disable these based on a flag (user-defined flags don’t seem to be possible in dune, so we were thinking to use a specific profile for the “full” set of backends, else use a reduced set).

Calling the preprocessor seems to work okay, however the libraries field needs to be dynamic based on the profile we choose, e.g.:

(libraries backend1 backend2 backend3)

But we might only want backend1 for our lightweight version. Is there a way to dynamically change libraries based on the current profile?

It might be that the design of the libraries isn’t set up well to allow this, so would appreciate advice there.

Another thing we want to be able to do is statically compile the final executable (that depends on the main library), so I think that rules out DynLink type things.

Thanks for your help!

At the moment there isn’t anything “built-in” that would allow this. However, you can achieve it using “OCaml syntax” Other topics — dune documentation to generate the dune file at runtime depending on the value of your environment variable.

This kind of thing has been asked before and the plan is to enable it by allowing to include generated dune files, but this will not be available until after 3.0 is released later this year, at least.

Cheers,
Nicolas

Have you checked out dune virtual libraries? Virtual libraries & variants — dune documentation