简体   繁体   English

如何在OCaml文件中加载模块?

[英]How to load a module inside an OCaml file?

I wish to use module Std inside my OCaml .ml file. 我希望在我的OCaml .ml文件中使用模块Std

I tried #load "Std" , but the compiler complains. 我试过#load "Std" ,但编译器抱怨。

How can I load a module inside OCaml? 如何在OCaml中加载模块?

You must compile the module you wish to include first, provide the location of the compiled files to compilation commands of modules depending on it, then provide it in the final compilation command line. 您必须首先编译要包含的模块,根据它将编译文件的位置提供给模块的编译命令,然后在最终编译命令行中提供。

Let's consider for instance file foo/moduleA.ml : 我们考虑一下文件foo/moduleA.ml

let v = 1

and file bar/moduleB.ml : 和文件bar/moduleB.ml

open ModuleA
let w = v

The commands: 命令:

$ cd foo
$ ocamlc -c moduleA.ml
$ cd ..

will produce moduleA.cmo and moduleA.cmi . 将生成moduleA.cmomoduleA.cmi The former is the bytecode object of the module (like a .o file in for native object files, but containing bytecode data and text), the later is a bytecode compiled header, produced from an automatically generated .mli file. 前者是模块的字节码对象(如本机目标文件中的.o文件,但包含字节码数据和文本),后者是字节码编译头,由自动生成的.mli文件生成。 This bytecode header is necessary for the compiler to compile files which depend on ModuleA . 这个字节码头是编译器编译依赖于ModuleA文件所必需的。

$ cd bar
$ ocamlc -I ../foo -c moduleB.ml
$ cd ..

will succeed in producing moduleB.cmo , which depends on ModuleA , because the previous command has been successful, and because we indicate the compiler where to look for dependancies with the -I command line parameter, followed by the path of the first module. 将成功生成依赖于ModuleA moduleB.cmo ,因为前一个命令已经成功,并且因为我们指示编译器在哪里查找带有-I命令行参数的依赖项,然后是第一个模块的路径。

The last command below will produce a bytecode executable from both modules: 下面的最后一个命令将生成两个模块可执行的字节码:

$ ocamlc -I foo -I bar moduleA.cmo moduleB.cmo -o prog.byte

The modules must be provided in that order, to let the compiler know the dependancies first . 必须按顺序提供模块,以便让编译器首先了解依赖性。 The -I parameters this time indicate where to find the .cmo files. 此时-I参数指示在哪里可以找到.cmo文件。

In your case, you must therefore use the -I <location of std.cmi> for the compilation proper phase, and -I <location of std.cmo> (or std.cma , if it is a library) for the second phase (the link phase). 因此,在您的情况下,您必须使用-I <location of std.cmi>进行编译正确的阶段,并使用-I <location of std.cmo> (或std.cma ,如果它是库)用于第二阶段(链接阶段)。 If you can combine both phases in one command (ie. ocamlc -I foo foo/moduleA.ml bar/moduleB.ml -o prog.byte ), and if both cmo and cmi files are in the same directory, only one parameter will suffice. 如果你可以在一个命令中组合两个阶段(即ocamlc -I foo foo/moduleA.ml bar/moduleB.ml -o prog.byte ),并且如果cmocmi文件都在同一目录中,则只有一个参数将满足。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM