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?
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.
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)
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