简体   繁体   中英

Ocaml can't find Unix module

I (re-)installed Ocaml on OS X using the following steps:

> brew uninstall ocaml
> brew uninstall opam
> brew install ocaml
> brew install opam
> opam init
> eval `opam config env`
> opam switch 4.02.1
> opam install batteries core

I then tried to compile this program:

open Unix
open Printf

let main () =
    match fork () with
    | 0 -> printf "child\n"
    | pid -> printf "parent\n"

let _ = main ()

I compiled using this command:

ocamlc -o fork fork.ml

But I get an error:

File "fork.ml", line 1:
Error: Error while linking fork.cmo:
Reference to undefined global `Unix'

In fact, I was getting this error before reinstalling; that is why I reinstalled in the first place. But the problem persists and I am not sure how to fix it.

unix library is not linked by default, so you need to pass some linking flags, to make it work, eg,

 ocamlc unix.cma fork.ml -o fork

If you don't want to know anything about cma , you can use ocamlbuild , instead of ocamlc:

 ocamlbuild -lib unix fork.native

Or even more general

 ocamlbuild -pkg unix fork.native

The latter (with pkg option) would be a preferred way, since it will allow you to specify any package installed with opam . Eg, if you would ever try to use lwt , the you can just link with it with

 ocamlbuild -pkg lwt fork.native

对于那些在使用 OCaml 交互式顶层时遇到此错误的人,命令行语法类似于ocamlc所需的ocamlc

ocaml unix.cma

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM