2

I am using Dune for building OCaml projects and I'd like to build a standalone library for reusing it in other projects.

The root folder of the library is mylib and the library was initialized with dune init lib mylib src (after cd mylib).

The directory tree of mylib, the root of the project, is the following:

mylib
+---dune-project
│
+---src
        dune
        priv.ml
        mymodule.ml
        mymodule.mli

Here follows the content of the files.

mylib/dune-project:

(lang dune 2.7)

mylib/src/dune:

(library
 (name mylib))

mylib/src/priv.ml:

let rec loop a accu i =
  let n = Array.length a in
  if i = n then
    accu
  else
    loop a (accu + Array.unsafe_get a i) (succ i)

mylib/src/mymodule.mli:

val sum : int array -> int

mylib/src/mymodule.ml:

let sum a =
  Priv.loop a 0 0

After giving context and showing the content of each file of this toy example, the question follows:

  1. How can I build the library mylib and use it in another, separate project?

(For example, in another project, I'd consume the library with the following:

Open Mylib
let () =
  print_int (Mymodule.sum [1;2;3])

OR

let () =
  print_int (Mylib.Mymodule.sum [1;2;3])

)

With Dune, given the executable main, you would write the following dune file to use library mylib if it was published on Opam.

dune:

(executable
 (name main)
 (libraries mylib))
  1. After successfully building the library and linking it in another project, how can I hide or not expose some modules? For example, given the toy library of before, mylib, I would like to not expose and make inaccessible the module Priv (such that Priv would only be usable inside modules of mylib - like a protected/internal class in Java/C#).

I tried searching on Real World OCaml, Cornell CS3110 textbook, Dune documentation, OCaml Learn but, unless deeply nested, I found nothing.

Thank you very much for your help, if I didn't explain something in a clear way, please ask and I will try to explain better.

Oliver
  • 926
  • 2
  • 12
  • 31

1 Answers1

2
  1. In the root directory, these should be a file called mylib.opam with content similar to this one. Then, the (public_name mylib) s-expression should be added to library in mylib/src/dune. Finally, making sure to be in the root of the project, the library shall be built with dune build and installed with opam install ..
    For actually using the library in another project, even in a different dune workspace, all it's needed is to add (libraries mylib) to the dune file of project that will use the library.
  2. The (private_modules priv) s-expression should be added to library in mylib/src/dune. Then, mylib.ml needs to be created with the following content: module Mymodule = Mymodule: this will make sure that only Mymodule will be exposed under the package Mylib.
Oliver
  • 926
  • 2
  • 12
  • 31