I'm a newbie with OCaml and I'd like to put some of the code into another file, say foo.ml
, just as one would do in C++ or Python. But that part of code itself does not form a module.
I've included #use "foo.ml"
in the head of my main source file. But when I build my project using ocamlbuild
, it reports I/O error: "foo.ml: No such file or directory"
. But clearly foo.ml
is in the current working directory.
I wonder if anyone knows how to achieve that aim in OCaml and let my project be built, or if that is not a convention in OCaml? Any suggestion is welcome.
As you are probably aware, you can include other source files in C++ with the #include pre-processor directive. Essentially, whatever file we include in that statement gets copied and pasted into the current source file by the compiler. However, the compiler needs to know how to find the file.
As a rule this practice should be avoided. If you absolutely must #include source (and generally it should be avoided), use a different file suffix for the file. I thought I'd share a situation where my team decided to include .c files. Our archicture largely consists of modules that are decoupled through a message system.
Python Server Side Programming Programming In order to source a Python file from another python file, you have to use it like a module. import the file you want to run and run its functions. For example, say you want to import fileB.py into fileA.py, assuming the files are in the same directory, inside fileA you'd write
Here are the two types of file that can be included using #include: Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files.
#use "foo.ml"
is a directive for the interactive toplevel, it doesn't work with the compiler.
If you want to split your code in different files (which is a good idea and is strongly recommended in OCaml), then you should use the module system. Why do you say your code doesn't form a module? If your code consists only of single-use functions, they should be in the same file as the functions that use them. If your code is reusable, then it forms a module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With