$ cat hello.ml
#!/usr/bin/env ocamlrun ocaml
let rec main = print_string "Hello World!\n"
$ ./hello.ml
Hello World!
$ ocaml hello.ml
Hello World!
$ ocamlc -o hello hello.ml
File "hello.ml", line 1, characters 0-1:
Error: Syntax error
$ ocamlopt -o hello hello.ml
File "hello.ml", line 1, characters 0-1:
Error: Syntax error
Similar to Erlang, OCaml permits shebangs in scripted mode, but borks in compiled mode. Is there a more idiomatic shebang in OCaml, one that doesn't trigger a syntax error during compilation?
There is not a directive that I know of which works with both the toplevel and the OCaml compilers, but you can use ocamlscript as an in-between option.
http://martin.jambon.free.fr/ocamlscript.html
ocamlscript uses ocamlfind + ocamlopt in the background to (re-)compile your code when it is executed. With ocamlscript installed, you can use:
#!/usr/bin/env ocamlscript
It does not give you direct toplevel compatibility, but it allows you to avoid a separate compilation step with many programs. The web site has decent documentation and examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With