3
$ 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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Bah, ocamlscript fails to compile in Mac OS X. Error: could not find ocamlfind.
Do you have ocamlfind installed? It is required by ocamlscript.
Please be sure you have ocamlfind, which is very standard for OCaml and you should always have. I use ocamlscript on Mac all the time without problems.
Thanks. Incidentally, ocamlfind fails to install on Mac OS X, so I'll contact the author about that.
I've never had a problem compiling ocamlfind on OS X. You might want to try the ./configure && make && sudo make install route.
|
2

Just use sed as a preprocessor. To remove the shebang on the first line, if found, pass:

-pp 'sed "1 s/^#\!.*$//"'

to ocamlc or ocamlopt.

4 Comments

Thanks. I wouldn't want to require OCaml users to use special compilation flags just to handle shebang lines, but I'm glad you got this to work.
It would be cool if the compilers automatically stripped the shebang. Maybe a request for enhancement.
Could you ask them? You're more in the know, so they'll more likely listen to you.
ocamlc -pp "tail +2"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.