OCaml - 将程序编译为库

标签 ocaml

我有一个 OCaml 程序(带有一个 main 方法 - 它生成一个可执行文件),我想将它用作一个库。

我正在像这样编译我的程序:ocamlc -I someDir -g -unsafe lotsOfCmoFiles -o outputFile并且程序运行良好。

现在我正在删除使其成为可执行文件的行(类似于 let _ = ... )并添加 -a编译命令参数:ocamlc -a -I someDir -g -unsafe lotsOfCmoFiles -o outputFile.cma
但不知何故,我无法使用 ocamltop 加载生成的 .cma 文件和 ocamlbrowser显示一个空列表。当我尝试从 ocamltop 加载时:

# #load "outputFile.cma";;
Error: Reference to undefined global `Xyz'

而且我 100% 确定 xyz.cmo 包含在 lotsOfCmoFiles 中.

我在编译时是否给了一些错误的参数?否则,我应该怎么做才能在 ocamltop 中加载我的程序? (我将在另一个程序中使用这个库,我以 ocamltop 输出为例)

任何帮助将不胜感激。

编辑:所以感谢@cago,我终于可以编译和加载它,现在我可以加载我的库,当我不删除主要 let _ = ...当我加载 .cma 时,它会自动运行。 .

但我仍然无法打开任何模块。奇怪的是,这并没有引发异常
open Main

但是当我从模块 Main 调用一个函数时:
# someFun;;
Error: Reference to undefined global `Main'

ocamlbrowse仍然显示一个空列表。现在为什么呢?

EDIT2:我意识到open Main不会失败,因为我在同一个文件夹中有一个 Main 模块(即使我没有明确加载它)。如果我将 .cma 文件移动到其他地方并加载它,它可以工作(即 main 函数自动运行),但现在我无法打开任何模块,即使 ocamlobjinfo显示模块。

EDIT3:-我没有帮助:
$ ocaml
        OCaml version 4.00.1

# #load "lib.cma";;
ok
# open Lib;;
Error: Unbound module Lib
# 
$ ocaml -I libFolder    
        OCaml version 4.00.1

# #load "toylib.cma";;
ok
# open Lib;;
# fun;;
Error: Reference to undefined global `Lib'

最佳答案

您的 lotsOfCmoFiles 中的一些 cmo需要知道模块 Xyz。您需要注意您的 cmo 文件之间的依赖关系。

例如:

toto.ml:

let x = "toto"

标题.ml:
let y = Toto.x ^ " titi"

ocamlc -c toto.ml
ocamlc -c titi.ml
ocamlc -a  titi.cmo toto.cmo -o lib.cma (* here is  the probleme *)

# #load "lib.cma"
Error: Reference to undefined global `Toto'

因为titi依赖toto所以需要改变cmos的顺序:
ocamlc -a toto.cmo titi.cmo -o lib.cma 

# #load "lib.cma"
# Titi.y;;
 - : string = "toto titi"

编辑:

例如,如果您的 cma 在子目录中,当您调用 ocaml您需要指定路径:
ocaml -I subdir/ (* subdir which contains lib.cma *)

# #load "lib.cma"
# Toto.x;;
- : string = "toto"

关于OCaml - 将程序编译为库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15200450/

相关文章:

.net - F# 可以更新类中的不可变绑定(bind)(创建一个更改了指定绑定(bind)的新对象吗?)

ocaml - "Eval"OCaml 中的字符串

string - Ocaml 中的子字符串检查

functional-programming - 函数式语言中的质因数分解

performance - 与模式匹配相比,是否存在 `Option.bind` 的性能成本?

format - 在格式模块上配置更大的列数限制

installation - Ocaml OPAM 是否检测先前安装的 Ocaml 软件包?

algorithm - 创建快速指数函数

functional-programming - OCaml 中的 `string` 是否支持 UTF-8?

ocaml - 初始化一个 int64 变量