7

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?

prosseek
  • 182,215
  • 215
  • 566
  • 871
  • Note that in many languages you can define variables ahead of the main function, at the global scope, which will require code execution before the start of the main function. If you allow side effects to happen for global definitions, why not have any statement possible? – didierc Feb 25 '15 at 10:26
  • @didierc: Could you elaborate? – prosseek Feb 25 '15 at 15:06
  • Any language which supports objects has constructors for them, so if you declare instances at global scope, the runtime has 2 possibilities: create them ahead of running main, or lazily wait until the variable is actually accessed. [Java](http://stackoverflow.com/questions/8704423/when-static-variables-are-initialized-in-java) and [C++](http://stackoverflow.com/questions/17783210/when-are-static-and-global-variables-initialized) use the former for static global objects. In the case of Ocaml though, it's the functional nature of the language which allows it :) – didierc Feb 25 '15 at 17:03

2 Answers2

11

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.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
4

No, a main function is not needed in OCaml, and it does parse the code from start to end.

When you have multiple files, you would need to compile them in order (or using forward refs)

Secret
  • 3,291
  • 3
  • 32
  • 50