Cabal projects

cabal init

A real project starts with a directory and one command. Cabal asks a few questions and writes the skeleton:

mkdir todo && cd todo && cabal init

What does the package build: 1) Library * 2) Executable 3) Library and Executable 4) Test suite Your choice? [default: Executable]

Answer 2 for an executable, accept the defaults, and choose base as the only dependency for now.

The .cabal file

The generated todo.cabal is the project description. Four stanzas matter at this stage:

cabal-version: 3.0 name: todo version: 0.1.0.0 executable todo main-is: Main.hs hs-source-dirs: app build-depends: base ^>=4.20.2.0 default-language: Haskell2010

build-depends is the dependency list, and the version bounds are a promise about which versions your code was tested against. Keep them loose but present.

Build and run

Four commands cover the whole edit cycle. Cabal caches what it built, so the second run is fast:

cabal build

Resolving dependencies... Build profile: -w ghc-9.10.3 -O1 In order, the following will be built (use -v for more details): - todo-0.1.0.0 (exe:todo) (first run) Configuring executable 'todo' for todo-0.1.0.0... Preprocessing executable 'todo' for todo-0.1.0.0... Building executable 'todo' for todo-0.1.0.0... [1 of 1] Compiling Main ( app/Main.hs, dist-newstyle/build/x86_64-linux/ghc-9.10.3/todo-0.1.0.0/x/todo/build/todo/todo-tmp/Main.o ) [2 of 2] Linking dist-newstyle/build/x86_64-linux/ghc-9.10.3/todo-0.1.0.0/x/todo/build/todo/todo

cabal run todo

Hello, Haskell!

cabal repl

ghci> :t main main :: IO ()

cabal repl loads the project modules with the right paths and dependencies, which is why it beats a bare ghci once the project has more than one file.

Project layout

The conventional layout separates the program from the library so that tests can import the logic without running main:

todo/ ├── app/Main.hs ├── src/Todo.hs ├── test/Spec.hs ├── todo.cabal └── cabal.project

The executable depends on the library and does nothing but parse arguments and call it. That single decision is what makes the capstone testable in lesson 49.

The code on this page was run with GHC 9.10.3 and cabal-install 3.16.0.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev