Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 40 ยท Tooling and Libraries

Dune and opam: Building and Managing OCaml Projects

Set up real OCaml projects. Install opam, create switches, scaffold with dune init, write dune files for executables and libraries, add dependencies, use the REPL, utop and ocamlformat.

OCaml has a small, modern toolchain. opam is the package manager: it installs compilers and libraries. dune is the build system: it compiles your code, runs tests, builds documentation and finds dependencies. Together with the editor support from ocaml-lsp-server, ocamlformat and utop, they give you a complete workflow.

This lesson is about commands you run on your own machine. The site cannot run them, so the blocks are read-only and the Python stand-in at the end only simulates a dependency graph. Commands shown here are standard dune 3.x and opam 2.x ones.

Installing

On Linux and macOS install opam with your package manager (or the official install script), then initialise it:

Terminal
opam init                         # creates ~/.opam, picks a compiler
eval $(opam env)                  # puts ocaml and dune on PATH for this shell
opam install dune utop ocaml-lsp-server ocamlformat

On Windows, use the opam Windows installer or WSL. After this, ocaml -version prints the compiler version, such as 5.x.

Switches

A switch is an isolated OCaml installation with its own compiler and packages. Use one per project or per compiler version:

Terminal
opam switch create myproject 5.2.0     # new switch with that compiler
opam switch list
opam switch myproject                  # change the active switch
opam switch create . 5.2.0             # local switch stored in ./_opam

Switches are why "works on my machine" problems are rare in OCaml: each project can pin its own set of versions.

Packages

Terminal
opam search json              # find packages
opam install yojson           # install one
opam list                     # show installed
opam update && opam upgrade   # refresh the repository and upgrade
opam show yojson              # description and versions

The REPL: ocaml and utop

ocaml is the plain toplevel. utop adds history, completion and colours; it is what most people use for experiments:

OCAML
# let xs = [1; 2; 3];;
val xs : int list = [1; 2; 3]
# List.map (fun x -> x * 2) xs;;
- : int list = [2; 4; 6]

Phrases end with ;; in the REPL only; in source files you do not need them. Inside utop, #require "str";; loads a library, and #use "file.ml";; runs a file.

Creating a project with dune

Terminal
dune init project hello          # creates hello/ with bin/, lib/, test/ and dune-project
cd hello
dune build                       # compile everything
dune exec hello                  # run the executable
dune test                        # run tests
dune build @fmt --auto-promote   # format with ocamlformat
dune clean                       # remove _build

A typical layout:

TEXT
hello/
  dune-project          # project-wide settings
  hello.opam            # generated package description
  bin/
    dune                # executable stanza
    main.ml
  lib/
    dune                # library stanza
    hello.ml
  test/
    dune
    test_hello.ml

dune-project

LISP
(lang dune 3.10)
(name hello)
(generate_opam_files true)

(package
 (name hello)
 (depends
  (ocaml (>= 5.0))
  dune
  (alcotest :with-test)))

(generate_opam_files true) makes dune write the .opam file from this description so you maintain dependencies in one place.

dune files

An executable and a library that it uses:

LISP
; bin/dune
(executable
 (name main)
 (public_name hello)
 (libraries hello))

; lib/dune
(library
 (name hello)
 (libraries str))

The (libraries ...) field lists dependencies by their findlib names (str, unix, yojson, lwt). Dune works out the module order and the recompilation set itself, so you never write module lists or makefiles.

Module Foo in lib/foo.ml is exposed to other directories as Hello.Foo because dune wraps library modules in a namespace named after the library.

Useful stanzas

Stanza Purpose
(executable ...) / (executables ...) build programs
(library ...) build a reusable library
(test ...) an executable run by dune test
(rule ...) custom build rule (generate a file)
(preprocess (pps ppx_deriving.show)) enable ppx rewriters
(ocamlopt_flags (:standard -O3)) native compiler flags (-O3 only has an effect with flambda)

A dune-workspace file or dune build --profile release switches to the optimised release profile. In the default dev profile, many warnings are errors, so unused variables fail the build. Keep warnings on; relax a specific one only when you must, for example (flags (:standard -w -27)).

Watch mode

Terminal
dune build --watch     # rebuild on every save
dune test --watch      # rerun tests on change

Pair it with an editor running ocaml-lsp-server: you get type-on-hover, go-to-definition, completion and inline errors.

Formatting and documentation

Create an empty .ocamlformat file with a line such as version = 0.26.2, then run dune fmt. The formatter makes style arguments disappear. Doc comments (** ... *) become HTML with dune build @doc (requires odoc).

Dependencies and reproducibility

Terminal
opam install . --deps-only --with-test    # install what the project needs
opam lock .                               # write a lock file with exact versions

Commit dune-project and (if you want reproducibility) the .opam.locked file. Do not commit _build or _opam.

How the pieces fit

flowchart LR
    O["opam<br/>compilers, packages, switches"] --> D["dune<br/>build, test, doc, fmt"]
    D --> C["ocamlc / ocamlopt<br/>compiler"]
    L["ocaml-lsp-server"] --> E["editor"]
    D --> L
    D --> B["_build/default/...<br/>executables"]

Figure: opam provides tools and libraries, dune drives the compiler.

Stand-in: dune decides the build order

Dune reads the dependencies between your modules and builds them in a valid order, rejecting cycles. This Python stand-in does the same job with a topological sort:

Python Stand-in: build order from module dependencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

OCaml rejects dependency cycles between modules in the same way. If two modules need each other, move the shared types into a third module.

Common mistakes

  • Forgetting eval $(opam env) in a new shell, so dune is "not found".
  • Listing a library in (libraries ...) that is not installed in the current switch.
  • Editing files inside _build.
  • Installing everything in the global switch instead of a per-project switch.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is an opam switch?

    Switches let each project use its own compiler version and libraries.
  2. 2. Which command builds and runs the executable named hello?

    dune exec builds the target if needed and then runs it.
  3. 3. Where do you declare which libraries a program uses?

    The libraries field lists dependencies by findlib name.
  4. 4. What does (generate_opam_files true) do?

    Dune generates package metadata so you only maintain it in one place.

Summary

  • opam manages compilers and packages in switches. dune builds, tests, formats and documents projects.
  • dune init, dune build, dune exec, dune test and dune build --watch are the daily commands.
  • Dependencies go in dune-project and the (libraries ...) field of each stanza.
  • utop, ocaml-lsp-server and ocamlformat make the editor experience comfortable.

Next: Testing and Debugging OCaml Code