Compile multiple ocaml files

I’m sorry if similar question was already answered, I didn’t find any.
I wanted to ask how to compile multiple ocaml files.
I think kind of know how to do that using ocamlc command, but I get syntax error when (assume my files are file1.ml, file2.ml) in file1.ml I put the line
#use file2.ml;;
I need this line to use functions I declared in file2,
I know I can write file2.func but I really prefer not to.

Hi, the # directives are for running in the toplevel (for instance utop).
You might want to take a look at dune to build your programs more easily: https://dune.build/

To do it by hand, you can take a look at the relevant parts of the OCaml manual, about ocamlc (bytecode) and ocamlopt (native)


It is good practice to write File2.func to refer to func defined in File2.
If File2 is Too_long_to_type, you can declare a module alias

module A = Too_long_to_type

And then refer to the function func as A.func.
Otherwise, for everything that is defined in File2 to be directly accessible, you can open File2. This is sometimes justified, but it might make the code less clear.

2 Likes

Thanks for the reply, for now I do want to use the toplevel because I’m a student and some of the files we were introduced to were written in toplevel.

I still find it hard how to compile files using toplevel, from a search on google I can see that the directive for toplevel is ocaml (instead of ocamlc),
and it’s written like that:
ocaml options objects
when objects are file that end with .cmi or .cma
so how do I compile my .ml files?

Ok, so the toplevel works more like an interpreter, it is not used to compile files.
So going back to your example, you might define some functions in file.ml,
which you then want to use in some other code that depends on it.
You would start a toplevel session (by calling ocaml or utop on the command line),
and then in the interactive session, you can type #use "file.ml" to use these definitions.
However you cannot use that to compile the code that you passed through the toplevel.
I’m not sure if that clarifies anything or not…
There’s just been a nice reply to another topic that might help you:

2 Likes

The other option that may make things a touch easier is to start looking into the dune build system. You can define a library and then open it in utop via: dune utop (as far as I can remember).

If you haven’t used it already the dev.realworldocaml.org is a useful resource, the chapter dealing with how the compilation actually works is: https://dev.realworldocaml.org/files-modules-and-programs.html.

1 Like

Hi, did you take a look at https://caml.inria.fr/pub/docs/manual-ocaml/comp.html ?