My OCaml Journey — Hello World!

Chris Duncan
2 min readJul 7, 2021
Photo by Octavian Dan on Unsplash

In my previous post I gave an outline of how I set up my environment in order to start learning OCaml. In this post are the steps that I took to create a basic OCaml hello world executable while using the dune build system in the process.

I’m using Ubuntu 20.04 as my operating system therefore the terminal commands that follow work on that system. You might have to use different commands depending on your operating system.

Let’s do it

First of all, open a terminal and create a directory for your code to live in -

mkdir helloworld

Go to that directory -

cd helloworld

Use dune to create the code for your executable -

dune init exe helloworld

If all goes well you should see a message similar to this -

Success: initialized executable component named helloworld

At this point you should have a directory structure within the helloworld directory that looks like this -

├── _build
│ └── log
├── dune
└── helloworld.ml

‘_build’ is a directory that contains a file called ‘log’. This holds information about what dune has done.

‘dune’ is a file that contains directives that the dune build system will use to build the helloworld executable.

‘helloworld.ml’ is a file that contains OCaml code that will print out “Hello, World!” in the terminal. The contents of the file should look like this -

let () = print_endline "Hello, World!"

Ok, so now we have the code but we don’t yet have an executable to run. Let’s remedy that by building the helloworld executable -

dune build

If the build is successful then you should see a message like this -

Info: Creating file dune-project with this contents:
| (lang dune 2.9)

There will now be some more files and directories created within your directory structure. I won’t address them now but only draw your attention to the fact that there should be a file called ‘helloworld.exe’ in the ‘default’ directory under the _build directory. That is our shiny new executable that we can now run.

Notice that the executable has a .exe suffix, which is usually associated with Windows executables, even though I’m doing this on an Ubuntu system. That is a design decision made by the creators of dune. There is a way to create an executable without the .exe suffix using dune but I won’t deal with that here.

dune provides a command to run our executable -

dune exec ./helloworld.exe

Of course, you can run the executable directly by specifying the path. Assuming that you are in the helloworld directory -

./_build/default/helloworld.exe

Either way, your output should be -

Hello, World!

Next time, I’ll move on to something a bit more interesting.

--

--

Chris Duncan
0 Followers

IT industry veteran, lifelong learner and lover of simplicity over complexity