如何在运行时确定 OCaml 或 Jane Street Core 库的版本

How do you determine the version of OCaml or Jane Street Core library at runtime

我正在迁移到最新版本的 OCaml(和 Jane Street 的核心模块),但希望我的代码能够继续使用旧版本进行编译。为此,我想创建一个具有可移植功能的模块,根据版本映射到旧接口或新接口。查询 OCaml 的版本和 Jane Street Core 的版本都可以。

我们如何在运行时查看编译器或 Jane Street Core 的版本?我知道我可以通过我的构建系统传递 ocamlopt --version 的输出,但理想情况下我不必以特殊方式调用我的程序。

您可以使用 Sys.ocaml_version 检索 OCaml 版本号。

utop # Sys.ocaml_version;;
- : string = "4.13.1"

恐怕在浏览了 Jane Street Base and Core API 文档后,我没有看到在运行时查询版本号的方法。

你可以使用 Config.version 来自 Compiler_libs 如此处记录 https://ocaml.org/api/compilerlibref/Config.html

注意 这个警告来自 Compiler_libs:

This library is part of the internal OCaml compiler API, and is not the language standard library. There are no compatibility guarantees between releases, so code written against these modules must be willing to depend on specific OCaml compiler versions.

很抱歉回答一个稍微不同的问题,但这可能是一个 XY 问题:如果你想构建一个兼容包,在运行时确定包的版本并没有真正帮助,因为像

let f = if Sys.ocaml_version > ... then new_function else compat_function 

要求 new_function 独立于 Sys.ocaml_version 的运行时值而存在。

兼容性包的一个常见解决方案是在构建时更早地使用 cppo 或使用一些代码生成来检测版本,例如参见 [​​=13=]。