[英]Include OCaml module in both interpreted and compiled modes
Say I have some OCaml code where I need to use the Str
module. 假设我有一些需要使用
Str
模块的OCaml代码。 If I run the code with the interpreter, then I have to put #load Str.cma
to be able to use the Str
module. 如果使用解释器运行代码,则必须放入
#load Str.cma
才能使用Str
模块。 But if I want to native-compile the code, then the load
directive causes an error. 但是,如果我想对代码进行本机编译,那么
load
指令将导致错误。 How can I import the module in a way that will work in both cases? 如何以在两种情况下都可以使用的方式导入模块?
I'm looking for either 我在找
(a) a way to include the module that works in both modes; (a)包括在两种模式下均可工作的模块的方式; or
要么
(b) a way to load the module for the interpreter that will be ignored by the compiler, leaving me to specify it on the command line. (b)一种为解释器加载将被编译器忽略的模块的方法,让我在命令行上指定它。
You can use OCaml in a scripting way (using the ocaml
binary, called toplevel), like you are describing. 您可以像描述的那样以脚本编写方式使用OCaml(使用
ocaml
二进制文件,称为顶级)。 Scripts have the advantage that the code is readily accessible and changeable. 脚本的优点是代码易于访问和更改。 But some problems arise:
但是会出现一些问题:
So there is no compatible syntax for ocaml toplevel and compiler invocation. 因此,没有针对ocaml顶级和编译器调用的兼容语法。 Command line arguments for the toplevel would require another wrapper script.
顶层的命令行参数将需要另一个包装脚本。
My recommendation: 我的建议:
Compiling is quite simple for ocaml programs once you know how to specify the components. 一旦知道了如何指定组件,对于ocaml程序,编译就非常简单。
As a side note: there is an opam package called ocamlscript that gives you a specific syntax for your packages and dependencies in a sort of script header, but compiles your script transparently to disk. 附带说明:有一个名为ocamlscript的opam软件包,可在某种脚本标头中为您的软件包和依赖项提供特定的语法,但可将脚本透明地编译到磁盘上。 Maybe this is what you want - but global opam install required.
也许这就是您想要的-但需要全局opam安装。
I wouldn't put #load
into the source file, it's not OCaml code. 我不会将
#load
放入源文件,这不是OCaml代码。 It's an instruction to the toplevel (as you know of course). 这是对顶层的指示(您当然知道)。
One possibility is to add the #load
commands you need to your ~/.ocamlinit
file. 一种可能是将所需的
#load
命令添加到~/.ocamlinit
文件中。 It doesn't hurt to load a few extra modules, so you can modify your ~/.ocamlinit
only occasionally as you work on different things. 加载一些额外的模块并没有什么坏处,因此您只能在处理其他事情时偶尔修改
~/.ocamlinit
。
如果您希望能够执行ocaml my_code.ml
并且my_code.ml
使用Str
模块,则只需执行ocaml str.cma my_code.ml
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.