【问题标题】:Separate compilation of OCaml modulesOCaml模块的单独编译
【发布时间】:2014-02-25 23:04:11
【问题描述】:

我已阅读this question 和其他人, 但是我的编译问题没有解决。

我正在使用这些文件测试单独的编译:

testmoda.ml

module Testmoda = struct
  let greeter () = print_endline "greetings from module a"
end

testmodb.ml

module Testmodb = struct
  let dogreet () = print_endline "Modul B:"; Testmoda.greeter ()
end

testmod.ml

let main () =
  print_endline "Calling modules now...";
  Testmoda.greeter ();
  Testmodb.dogreet (); 
  print_endline "End."
;;
let _ = main ()

现在我生成 .mli 文件

ocamlc -c -i testmoda.ml >testmoda.mli

testmoda.cmi 就在那里。

接下来我创建没有错误的 .cmo 文件:

ocamlc -c testmoda.ml

很好,对 testmodb.ml 做同样的事情:

strobel@s131-amd:~/Ocaml/ml/testmod> ocamlc -c -i testmodb.ml >testmodb.mli
File "testmodb.ml", line 3, characters 45-61:
Error: Unbound value Testmoda.greeter

再试一次:

strobel@s131-amd:~/Ocaml/ml/testmod> ocamlc -c testmoda.cmo testmodb.ml
File "testmodb.ml", line 3, characters 45-61:
Error: Unbound value Testmoda.greeter

其他组合也失败了。

如何编译 testmodb.ml 和 testmod.ml?这应该很容易 - 没有 ocamlbuild / omake / 绿洲,我想。

文件中的语法错误被排除, 如果我将它们放在一个文件中(之间有所需的空间),它会编译 并完美执行。

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    OCaml 在每个源文件的顶层免费为您提供一个模块。所以你的第一个模块实际上命名为Testmoda.Testmoda,函数命名为Testmoda.Testmoda.greeter,以此类推。如果你的文件只包含函数定义,事情会更好。

    顺便说一句,如果你要使用ocamlc -i 生成的界面,你真的不需要mli 文件。没有mli文件的界面和ocamlc -i生成的界面一样。如果您不想要默认界面,使用ocamlc -i 为您的 mli 文件提供了一个很好的起点。但是对于这样一个简单的例子,它只会让事情看起来比实际复杂得多(恕我直言)。

    如果您按照我的描述修改文件(删除额外的模块声明),您可以从头开始编译和运行,如下所示:

    $ ls
    testmod.ml  testmoda.ml testmodb.ml
    $ cat testmoda.ml
    let greeter () = print_endline "greetings from module a"
    $ cat testmodb.ml
    let dogreet () = print_endline "Modul B:"; Testmoda.greeter ()
    $ ocamlc -o testmod testmoda.ml testmodb.ml testmod.ml
    $ ./testmod
    Calling modules now...
    greetings from module a
    Modul B:
    greetings from module a
    End.
    

    如果您已经编译了一个文件(使用ocamlc -c file.ml),您可以在上面的命令中将.ml 替换为.cmo。即使所有文件名都是.cmo 文件,这也有效;在这种情况下,ocamlc 只是为您将它们链接在一起。

    【讨论】:

    • 哦奇迹,没有明确的模块定义它可以按预期工作,ocamlc -c testmoda.ml 创建 .cmi 和 .cmo ,后者可用于编译 testmod.ml - 单独编译。
    • (无法编辑评论)所以这里单独编译:ocamlc -c testmoda.ml;ocamlc -c testmodb.ml; ocamlc -o testmod testmoda.cmo testmodb.cmo testmod.ml
    • 请注意,我给出的单个命令也进行了单独编译:-) 它完全等同于这三个命令。但当然,有时您只想编译您展示的源文件之一。它也适用于testmod.ml
    猜你喜欢
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多