我有一个文件Tools.ml
,其中包含我自己编写的一些常见实用函数。在 .../Code/
下,我有几个文件夹,每个文件夹都包含一个项目。我的问题是我应该将这个 Tools.ml
放置在哪里,以便 .../Code/
下的所有文件夹和文件都可以通过 Open Tools< 共享此模块
.
希望我的问题很清楚...有人有好的解决方案吗?
编辑1:根据@gasche的回答,我编写了tools.ml
,如下所示:
module Tools =
struct
let a_function = ...
...
end
然后我编译了它,并按照建议完成了ocamlfind install tools META tools.cmotools.cmxtools.ml
,看起来进展顺利。然后我编写了 test.ml
如下:
open Tools
let f = Tools.a_function
然后我用ocamlc test.ml -o test
编译它,然后出现错误:
File "test.ml", line 1, characters 0-1:
Error: Error while linking test.cmo:
Reference to undefined global `Tools'
谁能告诉我发生了什么事吗?
最佳答案
您可以将其打包为独立库,与其他 OCaml 库一起安装,然后从项目中将其作为库进行访问。
一个非常简单的方法是为ocamlfind
编写一个META文件。 。在您可以轻松保存“个人库”项目的位置创建一个目录。假设您有 tools.ml
和tools.mli
,并且您的代码依赖于某些 findlib 包(例如 unix
和 bigarray
)。你的 META 看起来像这样:
name="tools"
description="personal collection of utilities"
version="0.1"
requires="unix,bigarray"
archive(byte)="tools.cmo"
archive(native)="tools.cmx"
一旦你写好了这个META文件,就很容易问ocamlfind
“安装”该库(如果需要的话可以删除它),并在其他项目中使用它。安装时,语法为 ocamlfind install <name> <meta-file> <file1> <file2> ...
哪里<file1>, <file2>..
是您希望看到包含在安装目录中的文件。您必须至少有tools.cmi
tools.cmo
(以及 tools.o
和 tools.cmx
用于 native 编译),但最好同时拥有 tools.mli
例如(如果您想提供代码, tools.ml
)。
ocamlfind install tools META tools.cmi tools.cmo tools.o tools.cmx tools.mli
(当然 tools.cmo
等必须存在,也就是说你编译完包后必须存在 install
。如果你使用过 ocamlbuild
,它们很可能位于 _build
子目录中,所以ocamlfind install ... _build/tools.cmo ...
.)
从您的众多项目中,您可以轻松地使用您的库,或者直接使用 ocamlfind 工具(如果您已经这样做来编译程序)
ocamlfind ocamlc -package tools ....
或通过 ocamlbuild
提供的设施例如,添加 package(tools)
到您的标签。
如果您对库进行了更改并希望从项目中访问它,则重新安装库
ocamlfind remove tools
ocamlfind install tools META ...
您也可以通过 oasis
处理这一切,它是 ocamlfind/ocamlbuild 之上的一层,用于自动化此过程。我对oasis
不够熟悉在我的脑海中给出这样的例子,但对于这样一个受限的情况(单文件库)来说它应该同样简单,并且如果您希望以后扩展您的库(例如,它还可以处理文档生成,预编译配置...)。
关于module - 在 OCaml 中哪里放置共享实用程序模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8663869/