Search code examples
moduleocamlread-eval-print-looptoplevel

How to load multiple OCaml files into toplevel?


I'm trying to debug a program I made. This is what my directory structure looks like:

src
 |- module1.ml
 |- section1
     |- module2.ml
     |- module3.ml

module1.ml is referenced by both module2.ml and module3.ml. module2.ml is referenced by module3.ml.

I've tried loading the files into the toplevel with the command

ocaml -I section1 module1.ml section1/module2.ml section1/module3.ml

but it doesn't work. It doesn't even bring up the toplevel or print an error. It does absolutely nothing and I am back to where I started with the Bash prompt.


Solution

  • If you want to run your code in this fashion, you're limited by the fact that the ocaml command expects any number of pre-compiled OCaml files (bytecode files) and one .ml file. If you supply multiple .ml files it ignores all but the first.

    The reason for your observed behavior is that your command line is asking for ocaml to run a file as a program. In other words, it's going to execute all the top-level code in the first .ml file (ignoring the rest) and then exit. I assume you don't have any top-level code that produces a visible result in your module1.ml file.

    You can make this work (or at least improve the situation) by compiling all but one of the files using ocamlc:

    $ ocamlc -c section1/module2.ml
    $ ocamlc -c section2/module3.ml
    $ ocaml section1/module2.cmo section1/module3.cmo module1.ml
    

    You can also load files into the toplevel after starting it up:

    $ ocaml
            OCaml version 4.10.0
    
    # #use "section1/module2.ml";;
    # #use "section1/module3.ml";;
    # #use "module1.ml";;
    # 
    

    This is what I usually do to experiment interactively with my code.

    If I just want to run the code, on the other hand, I compile all the files and then just run the result:

    $ ocamlc -o myprogram section1/module2.ml section1/module3.ml module1.ml
    $ ./myprogram