Ocaml (utop) on NixOS not detecting libraries

Hi, I’m trying to set up Ocaml to work with the Real World Ocaml book.

I can’t seem to get utop to detect installed libraries. Here’s my default.nix file so far:

with import <nixpkgs> {};

  ocamlPackages = pkgs.recurseIntoAttrs pkgs.ocamlPackages_latest;
  findlibSiteLib = "${ocamlPackages.findlib}/lib/ocaml/${ocamlVersion}/site-lib";
  ocamlVersion = (builtins.parseDrvName ocamlPackages.ocaml.name).version;
  ocamlInit = pkgs.writeText "ocamlinit" ''
    let () =
      try Topdirs.dir_directory "${findlibSiteLib}"
      with Not_found -> ()
    #use "topfind";;
    #require "base";;
    #require "core.top";;
    #require "core.syntax";;
  stdenv.mkDerivation rec {
    name = "rwo-shell";
    buildInputs = with ocamlPackages; [
    shellHook = ''
      alias utop = "utop -init ${ocamlInit}""
  1. run utop
  2. run open Base;;
  3. Get error: Error: Unbound module Base

Am I missing something here?

I haven’t used OCaml for some time, but I think that utop has its own handling of the require directive and you shouldn’t use #use "topfind";; (nor #thread;; afair) with it because it will break the native directive.

I tried without the custom ocamlInit and that seems to fix your problem

It turns out that Nix wasn’t the cause of the problem. i was using direnv to load the nix-shell, and direnv doesn’t run the shellHooks, which meant that when I ran utop it wasn’t with an ocamlinit, and hence couldn’t pick up the libraries.

I wrote a short post on how I ended up setting up OCaml and Emacs with NixOS here:


If anyone’s struggling with the same issues I had.

There was also some discussion in this issue: OCaml findlib doesn't install topfind · Issue #16085 · NixOS/nixpkgs · GitHub

And there is also this pull request: findlib: make scripts using `#use "topfind"` work by xplat · Pull Request #45799 · NixOS/nixpkgs · GitHub