The main function in OCaml

ocaml, program-entry-point, scala

Solution

OCaml is vaguely like a scripting language in that any top-level expressions are evaluated when you start up the program. It's conventional to have a function named `main` that invokes the main work of your program. But it's not necessary at all.

Expressions are evaluated in the order that the OCaml files appeared in when they were linked into an executable. Very often this means that the call to `main` is the last thing that happens when starting the program. Other files often appear before the one containing `main`, and any top-level code of these files will be executed first.

Problem

From a programmer trained in a C world, this is my main method for OCaml. ``` let main () = Printf.printf "Hello, world - %d %s\n" (Array.length Sys.argv) Sys.argv.(0) ;; main () ``` However, this code just works fine with ocaml/ocamlc/ocmalopt. ``` Printf.printf "Hello, world - %d %s\n" (Array.length Sys.argv) Sys.argv.(0) ;; ``` What's the logic behind this? Is OCaml something like script language (even though it compiles into binary with ocamlc or ocamlopt) in that it doesn't need main function? Compared to Scala, we can extend from App in order not to define main method. ``` object Hello extends App { class A println(new A() getClass()) print("Hello, world") } ``` Even in this case, we need to have `Hello.main(args)` when executing it in interpreter mode: i.e., `scala hello.scala`. OCaml doesn't seem to need any change in ocaml (interpreted), ocamlc and ocamlopt (compiled). So, do we need main function in OCaml? If so, does OCaml just generates code from the start of the code to the end? If so, how OCaml finds the main code with multiple source code?

Original source

Related problems