How to debug when I need to open several modules?

Hi everyone! I just start to learn OCaml.
The problem I have is that I need to open some modules in my example.ml file. I saw that the command ocamlfind ocamlc -package batteries -linkpkg example.ml -o example does work. But if I want to debug my program, the command is too long to input. Is there some way to debug easier? The modules opened are installed by opam install xxx`.

Hi @Hsingi5

Sorry this question has been left unanswered, welcome to the OCaml community! I’m going through learning posts for a different project and came across this. I really hope you got your question answered, but seeing as I’m going through this I thought I would add it here in case it helps others.

Utop Solution

If you are looking for trying out packages installed using opam (like batteries in your example) then I highly recommend using utop the universal toplevel for OCaml.

$ opam install utop 
$ opam install batteries
$ utop 

Once in a utop session you can pull in these packages to explore using the #require directive which is specific to the toplevel (it won’t work in OCaml files being compile with something like dune).

utop # #require "batteries";;
utop # open Batteries;;
utop # Array.create;;
- : int -> 'a -> 'a array = <fun>
utop # Array.create 5 "hi";;
- : string array = [|"OCaml"; "OCaml"; "OCaml"; "OCaml"; "OCaml"|]

Note opening Batteries exposes all of the submodules like Array.

If you want to open your own file then you will need to use the #use directive.

utop # #use "myfile.ml"

If your example is more complicated and uses multiple files (modules) to do what it needs to do then I recommend reading on to the dune solution.

Dune Solution

Whilst you can use the original OCaml commands likes ocamlfind and ocamlc these can quickly become very unwieldy as you add more and more dependencies, files etc. as you discovered I recommend using a build-tool like dune to make your life easier.

In a fresh directory you can run:

$ opam install dune
$ dune init exec example --libs batteries

Which should give you:

.
|-- _build
|-- dune
`-- example.ml

From here you can run dune exec -- ./example.exe which will print "Hello World" as that is the default example it adds. But if you look inside the dune file you’ll see an executable stanza:

(executable
 (name example)
 (libraries batteries))

(name example) is the entry-point and (libraries batteries) specifies the other packages you want to use. The _build directory is used by dune. If you run dune build this will put the executable in _build/default/example.exe. Now you have all the power of dune if you need it but also adding more packages, changing them, adding more .ml files etc. is straightforward.

Further Reading