Hello World (first programs) · Beginner · 16 min
Hello World in OCaml: opam, utop and a dune project
By Padding · Updated 18 Nov 2026
Debian 13 (ocaml/opam:debian-13-ocaml-5.5 image) · OCaml 5.5.2 · opam 2 · dune 3
You will install OCaml 5.5 with opam, run Hello World as a script, compile it to bytecode and native code, and build a dune project with a greet function whose type OCaml works out for you.
On this page
OCaml is a statically typed functional language from France's INRIA research institute, in continuous use since 1996. Its best-known trick is type inference: the compiler checks the type of every value in your program, so a string can never be passed where a number is expected, yet you almost never write a type yourself. It works the types out from how you use each value.
OCaml also gives you a choice most languages do not. It ships with two compilers: ocamlc turns your code into portable bytecode that runs on a small virtual machine, and ocamlopt turns it into a native program for your processor. Since version 5.0, the runtime is multicore: one OCaml program can run code on several processor cores at once using domains.
You need three tools. opam is the package manager: it installs compilers and libraries into separate environments called switches. dune is the build tool used by nearly every OCaml project. utop is an improved interactive toplevel, where you type OCaml and see each result and its type straight away.
In this tutorial you install opam and OCaml 5.5, run Hello World three ways, try utop, then create a dune project with a function that greets the reader by name. The code was written for OCaml 5.5.2 and runs on any OCaml from 4.14 onwards.
Step 1 · Install opam and create an OCaml 5.5 switch
opam builds OCaml from source, so it needs a C compiler and a few helpers. On Ubuntu 26.04 or Debian 13, install them together with opam:
sudo apt update
sudo apt install -y build-essential curl git unzip bubblewrap opambuild-essential provides the C compiler and linker, git and unzip let opam fetch packages, and bubblewrap is the sandbox opam uses so that a package's build script cannot write outside its own folder. Your distribution's opam may be a little behind the newest release; any opam 2.1 or later works. For the newest opam, use the official script from ocaml.org/install instead of the opam package:
bash -c "sh <(curl -fsSL https://opam.ocaml.org/install.sh)"On macOS, install Homebrew and run brew install opam. On Windows, run winget install Git.Git OCaml.opam in PowerShell, then continue with opam init --bare below in a new terminal.
Now set up opam for your user. This creates the folder ~/.opam, downloads the list of available packages, and asks whether to add a line to your shell's start-up file. Answer y, so new terminals find OCaml on their own:
opam init --bare--bare tells opam not to build a default compiler yet, so OCaml is compiled only once, in the next command. Create a switch for OCaml 5.5.2 by name, so you know exactly what you have, and load it into the current shell:
opam switch create 5.5 ocaml-base-compiler.5.5.2
eval $(opam env --switch=5.5)opam switch create compiles OCaml from source. It takes between a few minutes and a quarter of an hour, depending on your machine. Each switch lives in its own folder under ~/.opam, with its own compiler and libraries, so two projects can use different OCaml versions without interfering. opam env prints the environment variables, mainly PATH, that point your shell at the switch, and eval applies them.
If you pay for data by the megabyte, create one switch and keep reusing it. Every new switch downloads and compiles the compiler again, and every library you install is fetched once per switch.
Check it worked
opam switch list shows a table with a switch called 5.5 and an arrow (→) in front of it, marking it as the one in use. opam --version prints a version starting with 2..
Step 2 · Check the compiler and toolchain
Ask OCaml which version you have and where it lives:
opam --version
ocaml -version
ocamlopt -version
which ocamlocaml is the toplevel, the interactive interpreter. ocamlopt is the native compiler. which ocaml should point inside ~/.opam: if it prints /usr/bin/ocaml instead, an older OCaml from your distribution is earlier on your PATH, and you need to run eval $(opam env) again.
Check it worked
ocaml -version prints The OCaml toplevel, version 5.5.2 and ocamlopt -version prints 5.5.2. A newer 5.5 patch release is fine.
Step 3 · Write Hello World and run it as a script
Make a throwaway folder and write the program:
mkdir -p ~/ocaml-demo
cd ~/ocaml-demo
cat > hello.ml <<'ML'
let () = print_endline "Hello, World!"
ML
ocaml hello.mlThat one line is a complete OCaml program. Reading it from the left:
letgives a name to a value. Everything in an OCaml file is a series ofletdefinitions, run from top to bottom.()is the unit value, the only value of the typeunit. It means "nothing useful", much likevoidin C or Java. Writinglet () =says: "run the expression on the right, and check that its result is unit". It is how OCaml marks the code a file runs, so there is nomainfunction to declare.print_endlineis a function from the standard library that prints a string followed by a newline."Hello, World!"is a string, the function's argument. OCaml calls functions by writing the argument after the name, with a space: no brackets and no commas.f xmeans "callfwithx".
ocaml hello.ml hands the file to the toplevel, which compiles it to bytecode in memory and runs it at once. Nothing is written to disk, which makes it handy for small scripts.
Check it worked
The terminal prints Hello, World! and ls shows only hello.ml: running a script leaves no files behind.
Step 4 · Compile to bytecode and to native code
Now compile the same file with each compiler:
ocamlc -o hello.byte hello.ml
ocamlopt -o hello hello.ml
./hello.byte
./hello
ls
head -n 3 hello.byteocamlc -o hello.byte hello.mlmakes a bytecode program. It starts with a short launcher that findsocamlrun, the bytecode virtual machine. In OCaml 5.5 the launcher is a small shell script, sohead -n 3shows#!/usr/bin/shfollowed by lines namingocamlrunand its folder inside~/.opam(the exact form varies between OCaml versions). It runs anywhereocamlrunof the same version is installed, on any processor.ocamlopt -o hello hello.mlmakes a native program for your processor. It starts faster and runs faster, and it needs no OCaml installation to run, so you can copy it to another Linux machine of the same kind.
The other files are the compilers' working files:
hello.cmiis the compiled interface: the list of names and types the moduleHellomakes available to other files. Every.mlfile is a module named after the file, with a capital letter.hello.cmois the bytecode object file andhello.cmxwithhello.oare the native ones.
On a real project you never manage these by hand; dune does it for you, as you will see shortly. If you see ocamlfind ocamlopt -package ... in older guides, that is the same compiler with a helper that finds installed libraries; dune has replaced it for most work.
Check it worked
Both ./hello.byte and ./hello print Hello, World!. ls lists hello, hello.byte, hello.cmi, hello.cmo, hello.cmx, hello.ml and hello.o, and the first lines of hello.byte are a short launcher script that mentions ocamlrun, something like r='ocamlrun-a100'.
Step 5 · Install dune and utop and try the toplevel
Install both tools into the current switch. The first run downloads and compiles them and their libraries, which takes a few minutes:
opam install -y dune utop
dune --versionAt the time of writing that installs dune 3.25.0 and utop 2.18.0; any dune 3 works for this tutorial.
Start utop and type the lines after the # prompt. Each one ends with ;;, which tells the toplevel "run this now":
utop# 1 + 2;;
- : int = 3
# let greet name = "Hello, " ^ name ^ "!";;
val greet : string -> string = <fun>
# greet "Amina";;
- : string = "Hello, Amina!"
# #quit;;Read the answers carefully, because they are the point of utop:
- : int = 3means "an unnamed value (-) of typeint, equal to 3".^joins two strings. OCaml uses a different operator for each type:+adds integers,+.adds floating-point numbers, and^joins strings. That is part of what lets it infer types without help.val greet : string -> string = <fun>is the type OCaml inferred. You never saidnamewas a string, but you joined it to other strings with^, so it must be one, and the result must be one too.string -> stringreads "takes a string, returns a string".#quit;;leaves utop. Ctrl+D does the same.
The plain ocaml toplevel answers the same way, with fewer comforts: utop adds history, colour, and completion with the Tab key.
Check it worked
dune --version prints a version starting with 3.. In utop, typing greet "Amina";; answers - : string = "Hello, Amina!".
Step 6 · Create a dune project with a greet function
Ask dune for a new project called greeter:
cd ~/ocaml-demo
dune init project greeter
cd greeter
ls
cat bin/dune
cat bin/main.mldune init project lays out the standard shape of an OCaml project:
dune-projectmarks the project root and states which version of dune's rules it uses.bin/holds the program.bin/dunesays to build anexecutablefrommain.mland install it under thepublic_namegreeter.lib/is for library code you want to share, andtest/is for tests. For nowlib/holds only adunefile declaring alibrary, andtest/holds adunefile and an emptytest_greeter.ml: no code yet.greeter.opamdescribes the project as an opam package, so others could install it.
bin/main.ml already contains the one-line Hello World you wrote by hand. Replace it with a version that asks for a name:
cat > bin/main.ml <<'ML'
let greet name =
if name = "" then "Hello, stranger!" else "Hello, " ^ name ^ "!"
let () =
print_string "What is your name? ";
let name = String.trim (read_line ()) in
print_endline (greet name)
ML
dune build
echo "Chidi" | dune exec greeterLine by line:
let greet name = ...defines a function calledgreetwith one argument,name. There are no type annotations.if name = "" then ... else ...chooses one of two strings. In OCamlifis an expression that produces a value, and both branches must have the same type. A single=compares values; it does not assign anything, because OCaml variables do not change once they are defined.print_stringprints without a newline, so the answer appears on the same line as the question.- The
;after it means "do this, then do the next thing". It goes between two actions, not after every line. read_line ()prints anything waiting to be shown, then reads one line from the keyboard and returns it without the newline. The()is there becauseread_linetakes the unit value as its argument: calling it with "nothing" is what tells OCaml to run it now.String.trimremoves spaces from both ends.Stringis the standard library's string module, and the dot reaches into it.let name = ... innames a value for the expression that followsin. This is how you make a local variable.print_endline (greet name)needs the brackets: without them, OCaml would readprint_endline greet nameas passing two arguments toprint_endline.
dune build compiles everything into a hidden _build folder, and dune exec greeter builds if needed, then runs the program. echo "Chidi" | types the name for you; run dune exec greeter on its own to type it yourself. Names with accents or in other scripts, such as Adébáyọ̀ or Ọlá, print back correctly, because OCaml strings hold the UTF-8 bytes you type unchanged.
Now ask the compiler to show the type it inferred for greet:
ocamlc -i bin/main.ml-i prints the interface of a file, the names it defines and their types, without compiling anything.
Check it worked
dune build prints nothing, which means success. The program prints What is your name? Hello, Chidi! on one line, and pressing Enter without a name prints Hello, stranger!. ocamlc -i bin/main.ml prints val greet : string -> string.
Step 7 · Read a type error
Type errors are where OCaml earns its keep, so it is worth reading one on purpose. Add a line that uses +, the integer operator, on a string:
cat > bin/main.ml <<'ML'
let greet name =
if name = "" then "Hello, stranger!" else "Hello, " + name
let () = print_endline (greet "Chidi")
ML
dune build 2> errors.txt || echo "Build failed, as expected"
cat errors.txtThe message names the file, line and characters, quotes the code with the problem underlined, and ends with an Error: line that says something like: the constant "Hello, " has type string but an expression was expected of type int. OCaml saw +, so it expected integers on both sides, and "Hello, " is not one. The program never ran: this mistake cannot reach your users.
Fix it by putting ^ back, and build again:
cat > bin/main.ml <<'ML'
let greet name =
if name = "" then "Hello, stranger!" else "Hello, " ^ name ^ "!"
let () = print_endline (greet "Chidi")
ML
dune build
dune exec greeterCheck it worked
The first build prints Build failed, as expected and errors.txt contains an Error: message that mentions both types, string and int (long messages wrap, so int may sit alone on the next line). After the fix, dune exec greeter prints Hello, Chidi!.
Common beginner mistakes
- Forgetting
eval $(opam env)in a new terminal when you skipped the shell hook duringopam init. You then getocaml: command not found, or an older system OCaml. - Using
;;in.mlfiles. It is only needed in the toplevel; in files, dune and the compilers do not need it. - Putting
;after the last action in a sequence, or beforein.;goes between two actions, and a stray one usually gives a syntax error on the next line. - Joining strings with
+, as above, or adding a whole number to a decimal one:1 + 2.5is a type error, so convert first withfloat_of_int 1 +. 2.5. - Leaving a variable unused. In a dune project, the default development build treats warnings such as
unused variableas errors, so delete the variable or start its name with_.
Step 8 · Know where OCaml is used and clean up
OCaml shows up where correctness matters more than popularity:
- Compilers and language tools: OCaml's pattern matching and types suit programs that read and transform other programs. The first Rust compiler was written in OCaml, and so are the Haxe compiler and Meta's Flow type checker.
- Formal verification: the Rocq proof assistant (formerly Coq), used to prove software and mathematics correct, is written in OCaml.
- Finance: Jane Street, a trading firm, writes most of its systems in OCaml and publishes many of its libraries as open source.
- Static analysis: Meta's Infer, which looks for bugs in Java, C and Objective-C code before it ships, is written in OCaml.
When you have finished, remove the tutorial folder:
cd ~
rm -rf ~/ocaml-demoThe switch, dune and utop stay installed for your next project. To remove the switch as well, run opam switch remove 5.5.
Check it worked
ls ~/ocaml-demo reports No such file or directory, while ocaml -version still prints version 5.5.2: deleting a project does not touch the switch.
Next steps
- Meet another statically typed functional language, with a stricter line between pure code and input and output: Hello World in Haskell.
- See OCaml's closest relative on .NET, which borrows much of its syntax: Hello World in F#.
- Compare with a language that took ideas from OCaml into systems programming: Hello World in Rust.
- Try the OCaml 5 multicore runtime: the Domain module in the standard library runs a function on another core, and the "Parallel programming" chapter of the OCaml manual walks through it.
Related tutorials
- Hello World in Haskell: GHCup, ghci and IOYou will install GHC 9.14 with GHCup, try expressions in ghci, run and compile Hello World, and write a program that keeps a pure greet function apart from the IO that reads your name.
- Hello World in F#: dotnet, printfn and F# scriptsYou will create and run an F# 10 console app with the .NET 10 SDK, run the same idea as an F# script with dotnet fsi, and extend it with a greet function, the pipeline operator and pattern matching on the command-line arguments.
- Hello World in Rust: rustup, Cargo and your first crateYou will install Rust 1.100 with rustup, create and run a Cargo project, compare debug and release builds, and read a number from the keyboard with proper error handling.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials