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

I am new to OCaml and I would like to put part of the code in another file, say foo.ml , like in C ++ or Python. But this piece of code alone does not form a module.

I included #use "foo.ml" at the beginning of my main source file. But when I create my project using ocamlbuild , it reports I/O error: "foo.ml: No such file or directory" . But it is clear that foo.ml is in the current working directory.

I wonder if anyone knows how to achieve this goal in OCaml, and let my project be built, or if it is not an agreement in OCaml? Any suggestion is welcome.

+4
source share
2 answers

#use "foo.ml" is a directive for the interactive top level; it does not work with the compiler.

If you want to split your code into different files (which is a good idea and highly recommended in OCaml), you should use a module system. Why are you saying that your code does not form a module? If your code consists of only one-time functions, they should be in the same file as the functions that use them. If your code is reused, it forms a module.

+12
source

As Tomas said, this is probably the wrong solution to your problem.

If you need it, you should use camlp4 or external tools like cppo .

example for pa_macro (comes with ocaml):

test2.ml:

 let arg = "Hello World" 

test.ml:

 INCLUDE "test2.ml" let () = print_endline arg 

compilation:

  ocamlfind ocamlc -syntax camlp4o -package camlp4 -ppopt pa_macro.cmo test.ml -o test 
+3
source

Source: https://habr.com/ru/post/1481236/


All Articles