Hello World is the first program written by developers to learn programming language.
It is easy and quick to code a language in Ocaml.
This post covers
- Writing a simple hello world program
- Print the string to the console
- Compile and execute a program using the command line.
How to write a Hello World program in OCaml?
- Open any editor
- Create a file called HelloWorld.ml, where ml is an extension for OCaml code.
- Add the below lines of code
(* HelloWorld*)
(* Simple first OCaml example
** Hello world program print to console
*)
print_string "Hello world Welcome to OCaml programming\n"
Comments are single-line or block/multi-line comments.
Single lines are started with (*
, followed by single-line text and ends with *)
Multi-line comments span in multiple lines, starting with (*
and ending with *)
and each line of text starts with *
.
The print_string
function prints the string to standard output.
Unlike other programming languages, There is no main function in OCaml
How to compile and execute the program.
There are multiple ways to compile and execute a program.
The compiler compiles program code to bytecode or native code
ocamlopt
tool compiles the OCaml to native codeocamlc
compiles the code to byte codeOne way using the
ocamlopt
tool Theocamlopt
tool compiles the ocaml code into native code.
ocamlopt -o hello HelloWorld.ml
It generates the following files
hello.cmx hello.o Next, Execute native binary code as given below.
.//hello
Hello world Welcome to OCaml programming.
The second way using ocamlc
.
ocamlc
is an ocaml compiler also called byte code compiler.
It converts code into binary code.
ocamlc -o hello HelloWorld.ml
Next, run binary code using give below.
.//hello
Hello world Welcome to OCaml programming.
Similarly,
You can use the OCaml
tool to run the program without compiling the code to binary form.
ocaml HelloWorld.ml