Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include other source files using the #use directive in OCaml?

Tags:

ocaml

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.

like image 399
tfboy Avatar asked May 16 '13 17:05

tfboy


People also ask

How to include other source files in C++ with pre-processor?

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.

Should I include the source of a file in my project?

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.

How to source a Python file from another Python file?

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

What types of files can be included using “include”?

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.


1 Answers

#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.

like image 64
Thomash Avatar answered Sep 29 '22 16:09

Thomash