ocamltoplevelocaml-toplevel

Ocaml: unknown directive `require'


When loading OCaml, I receive this message when loading ocaml at the terminal:

   ocaml
    OCaml version 4.07.1

   Unknown directive `require'.

What is the problem exactly?


I had previously modified my ocamlinit file, because I had some problems. It now contains:

(* ## added by OPAM user-setup for ocamltop / base ## 3ec62baf6f9c219ae06d9814069da862 ## you can edit, but keep this line *)


(* Added by OPAM. *)                                                            

let () = try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH")
 with Not_found -> ()
;;

#require "yojson";;
#use "topfind";;
#camlp4o
#thread;;
Topfind.don't_load ["compiler-libs.toplevel"];;
#require "core.top";;
#require "core.syntax";;
(* ## end of OPAM user-setup addition for ocamltop / base ## keep this line *)

Edit:

I looked at this question before ocaml command line cannot find “topfind”, however I did not find it helpful, since nowhere in the answers was it specified that you need to run eval $(opam config env) every time before opening ocaml, as someone below has informed me. So I think this person's clarification is useful to have on this site for other people.


Solution

  • You shall put #use "topfind" before any #require directive. So put #require "yojson";; to the end of the .ocamlinit file (also it is a good idea to add it after the comment).

    The #require directive is provided by the ocamlfind tool via the topfind script, which is loaded into the toplevel via the #use directive, which is a standard builtin directive for loading files. The topfind file initializes the ocamlfind system in the toplevel, so that the toplevel now can access to the ocamlfind infrastructure and load libraries installed in the system. If you're using opam to install packages, then do not forget to do eval $(opam config env) (or a shorter version, available in opam 2.x eval $(opam env)) in your terminal, before starting the toplevel. E.g.,

    eval $(opam config env)
    ocaml
    

    and here is the correct contents of the .ocamlinit file:

    (* ## added by OPAM user-setup for ocamltop / base ## 3ec62baf6f9c219ae06d9814069da862 ## you can edit, but keep this line *)
    
    
    (* Added by OPAM. *)                                                            
    
    let () = try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH")
     with Not_found -> ()
    ;;
    
    
    #use "topfind";;
    #camlp4o
    #thread;;
    Topfind.don't_load ["compiler-libs.toplevel"];;
    #require "core.top";;
    #require "core.syntax";;
    (* ## end of OPAM user-setup addition for ocamltop / base ## keep this line *)
    
    #require "yojson";;