compiler-errorsocamlocamlfind

Unbound module Findlib error when I was compilering a Ocaml file which contains "open Findlib"


I wrote a Ocaml file which only contains one line code: open Findlib,and then I save the file and named it for test.ml.In the Ocaml64(Ocaml for windows) environment ,I typed command ocamlc -o test test.ml,there is an error: Error:Unbound module Findlib. But if I open the ocaml interactive enviroment and do it like this:

$ ocaml
        OCaml version 4.12.0
# #use "topfind"
  ;;
- : unit = ()
Findlib has been successfully loaded. Additional directives:
  #require "package";;      to load a package
  #list;;                   to list the available packages
  #camlp4o;;                to load camlp4 (standard syntax)
  #camlp4r;;                to load camlp4 (revised syntax)
  #predicates "p,q,...";;   to set these predicates
  Topfind.reset();;         to force that packages will be reloaded
  #thread;;                 to enable threads
# open Findlib;;
# 

it works,so I'am sure the Findlib library exists,I don't know why the error will happen when I compiling the file contains open findlib.


Solution

  • You need to link the findlib library to your executable. The ocamlfind utility can be used in a couple of ways to do this:

    ocamlfind ocamlc -package findlib -o test test.ml
    

    For example:

    $ cat test.ml
    open Findlib
    
    let () = print_endline "hello"
    
    $ ocamlfind ocamlc -package findlib -o test test.ml
    $ ./test
    hello
    $
    

    Or you can use ocamlfind to query where the library is located:

    $ ocamlfind query findlib
    /home/user/.opam/system/lib/findlib
    

    And then tell ocamlc to include that directory as a location to find libraries when linking your program.

    $ ocamlc -I /home/user/.opam/system/lib/findlib -o test test.ml
    $ ./test
    hello
    $ ocamlc -I `ocamlfind query findlib` -o test test.ml
    $ ./test
    hello
    $