Reference to undefined global 'Base' error

I tried running the following piece of code from Real World OCaml,

# require "base"
open Base
let distance (x1,y1) (x2,y2) =
  Float.sqrt ((x1 -. x2) **. 2. +. (y1 -. y2) **. 2.);;

If I have Base installed then why am I getting this error? How do I fix this?

Please explain what you did when you say “I tried running”, as there are several ways in which a piece of OCaml code can be executed.

If you tried compiling it (using ocamlc or ocamlopt), it sounds like a linking error. I’m not sure you can get this error using the toplevel. But you seem to be using toplevel directives (#require), so it is a bit confusing.


Sorry about the delay in replying.
If I haven’t messed up the installation procedure as mentioned,

#require "";;
#require "ppx_jane";;
open Base;;

I had this as the contents of .ocamlinit file under root directory.
Upon loading utop from VS Code terminal itself,
I get to see

I am kind of lost.

I typed the code inside a “” file. Things went smoothly as long as I didn’t use Base.

let x a b =

I can do

#use "";;
x 10 12

in utop. But running the first mentioned code is a problem.

Hi @Yash_Vaibhav, welcome!

The following should compile:

open Base
let distance (x1,y1) (x2,y2) =
  Float.sqrt ((x1 -. x2) **. 2. +. (y1 -. y2) **. 2.)

with ocamlfind ocamlopt -linkpkg -package base Check out Compiling OCaml Projects · OCaml Tutorials.

I know this is counterintuitive, but #require "base" is only valid in the “toplevel” (the OCaml REPL), as @nojb already explained. The double semicolons ;; is also a toplevel idiosyncrasy and although syntactically valid, should not be used in OCaml files.

1 Like

Thanks for the support.