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, in I put the line
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:

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.


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,
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 "" 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:


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 is a useful resource, the chapter dealing with how the compilation actually works is:

1 Like

Hi, did you take a look at ?