Welcome to the Cabal User Guide

Cabal is the standard package system for Haskell software. It helps people to configure, build and install Haskell software and to distribute it easily to other users and developers.

There is a command line tool called cabal for working with Cabal packages. It helps with installing existing packages and also helps people developing their own packages. It can be used to work with local packages or to install packages from online package archives, including automatically installing dependencies. By default it is configured to use Hackage which is Haskell’s central package archive that contains thousands of libraries and applications in the Cabal package format.

Introduction

Cabal is a package system for Haskell software. The point of a package system is to enable software developers and users to easily distribute, use and reuse software. A package system makes it easier for developers to get their software into the hands of users. Equally importantly, it makes it easier for software developers to be able to reuse software components written by other developers.

Packaging systems deal with packages and with Cabal we call them Cabal packages. The Cabal package is the unit of distribution. Every Cabal package has a name and a version number which are used to identify the package, e.g. filepath-1.0.

Cabal packages can depend on other Cabal packages. There are tools to enable automated package management. This means it is possible for developers and users to install a package plus all of the other Cabal packages that it depends on. It also means that it is practical to make very modular systems using lots of packages that reuse code written by many developers.

Cabal packages are source based and are typically (but not necessarily) portable to many platforms and Haskell implementations. The Cabal package format is designed to make it possible to translate into other formats, including binary packages for various systems.

When distributed, Cabal packages use the standard compressed tarball format, with the file extension .tar.gz, e.g. filepath-1.0.tar.gz.

Note that packages are not part of the Haskell language, rather they are a feature provided by the combination of Cabal and GHC (and several other Haskell implementations).

A tool for working with packages

There is a command line tool, called “cabal”, that users and developers can use to build and install Cabal packages. It can be used for both local packages and for packages available remotely over the network. It can automatically install Cabal packages plus any other Cabal packages they depend on.

Developers can use the tool with packages in local directories, e.g.

$ cd foo/
$ cabal install

While working on a package in a local directory, developers can run the individual steps to configure and build, and also generate documentation and run test suites and benchmarks.

It is also possible to install several local packages at once, e.g.

$ cabal install foo/ bar/

Developers and users can use the tool to install packages from remote Cabal package archives. By default, the cabal tool is configured to use the central Haskell package archive called Hackage but it is possible to use it with any other suitable archive.

$ cabal install xmonad

This will install the xmonad package plus all of its dependencies.

In addition to packages that have been published in an archive, developers can install packages from local or remote tarball files, for example

$ cabal install foo-1.0.tar.gz
$ cabal install http://example.com/foo-1.0.tar.gz

Cabal provides a number of ways for a user to customise how and where a package is installed. They can decide where a package will be installed, which Haskell implementation to use and whether to build optimised code or build with the ability to profile code. It is not expected that users will have to modify any of the information in the .cabal file.

For full details, see the section on building and installing packages.

Note that cabal is not the only tool for working with Cabal packages. Due to the standardised format and a library for reading .cabal files, there are several other special-purpose tools.

What’s in a package

A Cabal package consists of:

  • Haskell software, including libraries, executables and tests
  • metadata about the package in a standard human and machine readable format (the “.cabal” file)
  • a standard interface to build the package (the “Setup.hs” file)

The .cabal file contains information about the package, supplied by the package author. In particular it lists the other Cabal packages that the package depends on.

For full details on what goes in the .cabal and Setup.hs files, and for all the other features provided by the build system, see the section on developing packages.

Cabal featureset

Cabal and its associated tools and websites covers:

  • a software build system
  • software configuration
  • packaging for distribution
  • automated package management
    • natively using the cabal command line tool; or
    • by translation into native package formats such as RPM or deb
  • web and local Cabal package archives
    • central Hackage website with 1000’s of Cabal packages

Some parts of the system can be used without others. In particular the built-in build system for simple packages is optional: it is possible to use custom build systems.

Similar systems

The Cabal system is roughly comparable with the system of Python Eggs, Ruby Gems or Perl distributions. Each system has a notion of distributable packages, and has tools to manage the process of distributing and installing packages.

Hackage is an online archive of Cabal packages. It is roughly comparable to CPAN but with rather fewer packages (around 5,000 vs 28,000).

Cabal is often compared with autoconf and automake and there is some overlap in functionality. The most obvious similarity is that the command line interface for actually configuring and building packages follows the same steps and has many of the same configuration parameters.

$ ./configure --prefix=...
$ make
$ make install

compared to

$ cabal configure --prefix=...
$ cabal build
$ cabal install

Cabal’s build system for simple packages is considerably less flexible than make/automake, but has builtin knowledge of how to build Haskell code and requires very little manual configuration. Cabal’s simple build system is also portable to Windows, without needing a Unix-like environment such as cygwin/mingwin.

Compared to autoconf, Cabal takes a somewhat different approach to package configuration. Cabal’s approach is designed for automated package management. Instead of having a configure script that tests for whether dependencies are available, Cabal packages specify their dependencies. There is some scope for optional and conditional dependencies. By having package authors specify dependencies it makes it possible for tools to install a package and all of its dependencies automatically. It also makes it possible to translate (in a mostly-automatically way) into another package format like RPM or deb which also have automatic dependency resolution.

Configuration and Installing Packages

Configuration

Overview

The global configuration file for cabal-install is ~/.cabal/config. If you do not have this file, cabal will create it for you on the first call to cabal update. Alternatively, you can explicitly ask cabal to create it for you using

$ cabal user-config update

Most of the options in this configuration file are also available as command line arguments, and the corresponding documentation can be used to lookup their meaning. The created configuration file only specifies values for a handful of options. Most options are left at their default value, which it documents; for instance,

-- executable-stripping: True

means that the configuration file currently does not specify a value for the executable-stripping option (the line is commented out), and that the default is True; if you wanted to disable stripping of executables by default, you would change this line to

executable-stripping: False

You can also use cabal user-config update to migrate configuration files created by older versions of cabal.

Repository specification

An important part of the configuration if the specification of the repository. When cabal creates a default config file, it configures the repository to be the central Hackage server:

repository hackage.haskell.org
  url: http://hackage.haskell.org/

The name of the repository is given on the first line, and can be anything; packages downloaded from this repository will be cached under ~/.cabal/packages/hackage.haskell.org (or whatever name you specify; you can change the prefix by changing the value of remote-repo-cache). If you want, you can configure multiple repositories, and cabal will combine them and be able to download packages from any of them.

Using secure repositories

For repositories that support the TUF security infrastructure (this includes Hackage), you can enable secure access to the repository by specifying:

repository hackage.haskell.org
  url: http://hackage.haskell.org/
  secure: True
  root-keys: <root-key-IDs>
  key-threshold: <key-threshold>

The <root-key-IDs> and <key-threshold> values are used for bootstrapping. As part of the TUF infrastructure the repository will contain a file root.json (for instance, http://hackage.haskell.org/root.json) which the client needs to do verification. However, how can cabal verify the root.json file itself? This is known as bootstrapping: if you specify a list of root key IDs and a corresponding threshold, cabal will verify that the downloaded root.json file has been signed with at least <key-threshold> keys from your set of <root-key-IDs>.

You can, but are not recommended to, omit these two fields. In that case cabal will download the root.json field and use it without verification. Although this bootstrapping step is then unsafe, all subsequent access is secure (provided that the downloaded root.json was not tempered with). Of course, adding root-keys and key-threshold to your repository specification only shifts the problem, because now you somehow need to make sure that the key IDs you received were the right ones. How that is done is however outside the scope of cabal proper.

More information about the security infrastructure can be found at https://github.com/well-typed/hackage-security.

Legacy repositories

Currently cabal supports two kinds of “legacy” repositories. The first is specified using

remote-repo: hackage.haskell.org:http://hackage.haskell.org/packages/archive

This is just syntactic sugar for

repository hackage.haskell.org
  url: hackage.haskell.org:http://hackage.haskell.org/packages/archive

although, in (and only in) the specific case of Hackage, the URL http://hackage.haskell.org/packages/archive will be silently translated to http://hackage.haskell.org/.

The second kind of legacy repositories are so-called “local” repositories:

local-repo: my-local-repo:/path/to/local/repo

This can be used to access repositories on the local file system. However, the layout of these local repositories is different from the layout of remote repositories, and usage of these local repositories is deprecated.

Secure local repositories

If you want to use repositories on your local file system, it is recommended instead to use a secure local repository:

repository my-local-repo
  url: file:/path/to/local/repo
  secure: True
  root-keys: <root-key-IDs>
  key-threshold: <key-threshold>

The layout of these secure local repos matches the layout of remote repositories exactly; the hackage-repo-tool can be used to create and manage such repositories.

Building and installing packages

After you’ve unpacked a Cabal package, you can build it by moving into the root directory of the package and running the cabal tool there:

$ cabal [command] [option...]

The command argument selects a particular step in the build/install process.

You can also get a summary of the command syntax with

$ cabal help

Alternatively, you can also use the Setup.hs or Setup.lhs script:

$ runhaskell Setup.hs [command] [option...]

For the summary of the command syntax, run:

$ cabal help

or

$ runhaskell Setup.hs --help

Building and installing a system package

$ runhaskell Setup.hs configure --ghc
$ runhaskell Setup.hs build
$ runhaskell Setup.hs install

The first line readies the system to build the tool using GHC; for example, it checks that GHC exists on the system. The second line performs the actual building, while the last both copies the build results to some permanent place and registers the package with GHC.

Building and installing a user package

$ runhaskell Setup.hs configure --user
$ runhaskell Setup.hs build
$ runhaskell Setup.hs install

The package is installed under the user’s home directory and is registered in the user’s package database (setup configure --user).

Installing packages from Hackage

The cabal tool also can download, configure, build and install a Hackage package and all of its dependencies in a single step. To do this, run:

$ cabal install [PACKAGE...]

To browse the list of available packages, visit the Hackage web site.

Developing with sandboxes

By default, any dependencies of the package are installed into the global or user package databases (e.g. using cabal install --only-dependencies). If you’re building several different packages that have incompatible dependencies, this can cause the build to fail. One way to avoid this problem is to build each package in an isolated environment (“sandbox”), with a sandbox-local package database. Because sandboxes are per-project, inconsistent dependencies can be simply disallowed.

For more on sandboxes, see also this article.

Sandboxes: basic usage

To initialise a fresh sandbox in the current directory, run cabal sandbox init. All subsequent commands (such as build and install) from this point will use the sandbox.

$ cd /path/to/my/haskell/library
$ cabal sandbox init                   # Initialise the sandbox
$ cabal install --only-dependencies    # Install dependencies into the sandbox
$ cabal build                          # Build your package inside the sandbox

It can be useful to make a source package available for installation in the sandbox - for example, if your package depends on a patched or an unreleased version of a library. This can be done with the cabal sandbox add-source command - think of it as “local Hackage”. If an add-source dependency is later modified, it is reinstalled automatically.

$ cabal sandbox add-source /my/patched/library # Add a new add-source dependency
$ cabal install --dependencies-only            # Install it into the sandbox
$ cabal build                                  # Build the local package
$ $EDITOR /my/patched/library/Source.hs        # Modify the add-source dependency
$ cabal build                                  # Modified dependency is automatically reinstalled

Normally, the sandbox settings (such as optimisation level) are inherited from the main Cabal config file ($HOME/cabal/config). Sometimes, though, you need to change some settings specifically for a single sandbox. You can do this by creating a cabal.config file in the same directory with your cabal.sandbox.config (which was created by sandbox init). This file has the same syntax as the main Cabal config file.

$ cat cabal.config
documentation: True
constraints: foo == 1.0, bar >= 2.0, baz
$ cabal build                                  # Uses settings from the cabal.config file

When you have decided that you no longer want to build your package inside a sandbox, just delete it:

$ cabal sandbox delete                       # Built-in command
$ rm -rf .cabal-sandbox cabal.sandbox.config # Alternative manual method
Sandboxes: advanced usage

The default behaviour of the add-source command is to track modifications done to the added dependency and reinstall the sandbox copy of the package when needed. Sometimes this is not desirable: in these cases you can use add-source --snapshot, which disables the change tracking. In addition to add-source, there are also list-sources and delete-source commands.

Sometimes one wants to share a single sandbox between multiple packages. This can be easily done with the --sandbox option:

$ mkdir -p /path/to/shared-sandbox
$ cd /path/to/shared-sandbox
$ cabal sandbox init --sandbox .
$ cd /path/to/package-a
$ cabal sandbox init --sandbox /path/to/shared-sandbox
$ cd /path/to/package-b
$ cabal sandbox init --sandbox /path/to/shared-sandbox

Note that cabal sandbox init --sandbox . puts all sandbox files into the current directory. By default, cabal sandbox init initialises a new sandbox in a newly-created subdirectory of the current working directory (./.cabal-sandbox).

Using multiple different compiler versions simultaneously is also supported, via the -w option:

$ cabal sandbox init
$ cabal install --only-dependencies -w /path/to/ghc-1 # Install dependencies for both compilers
$ cabal install --only-dependencies -w /path/to/ghc-2
$ cabal configure -w /path/to/ghc-1                   # Build with the first compiler
$ cabal build
$ cabal configure -w /path/to/ghc-2                   # Build with the second compiler
$ cabal build

It can be occasionally useful to run the compiler-specific package manager tool (e.g. ghc-pkg) tool on the sandbox package DB directly (for example, you may need to unregister some packages). The cabal sandbox hc-pkg command is a convenient wrapper that runs the compiler-specific package manager tool with the arguments:

$ cabal -v sandbox hc-pkg list
Using a sandbox located at /path/to/.cabal-sandbox
'ghc-pkg' '--global' '--no-user-package-conf'
    '--package-conf=/path/to/.cabal-sandbox/i386-linux-ghc-7.4.2-packages.conf.d'
    'list'
[...]

The --require-sandbox option makes all sandbox-aware commands (install/build/etc.) exit with error if there is no sandbox present. This makes it harder to accidentally modify the user package database. The option can be also turned on via the per-user configuration file (~/.cabal/config) or the per-project one ($PROJECT_DIR/cabal.config). The error can be squelched with --no-require-sandbox.

The option --sandbox-config-file allows to specify the location of the cabal.sandbox.config file (by default, cabal searches for it in the current directory). This provides the same functionality as shared sandboxes, but sometimes can be more convenient. Example:

$ mkdir my/sandbox
$ cd my/sandbox
$ cabal sandbox init
$ cd /path/to/my/project
$ cabal --sandbox-config-file=/path/to/my/sandbox/cabal.sandbox.config install
# Uses the sandbox located at /path/to/my/sandbox/.cabal-sandbox
$ cd ~
$ cabal --sandbox-config-file=/path/to/my/sandbox/cabal.sandbox.config install
# Still uses the same sandbox

The sandbox config file can be also specified via the CABAL_SANDBOX_CONFIG environment variable.

Finally, the flag --ignore-sandbox lets you temporarily ignore an existing sandbox:

$ mkdir my/sandbox
$ cd my/sandbox
$ cabal sandbox init
$ cabal --ignore-sandbox install text
# Installs 'text' in the user package database ('~/.cabal').

Creating a binary package

When creating binary packages (e.g. for Red Hat or Debian) one needs to create a tarball that can be sent to another system for unpacking in the root directory:

$ runhaskell Setup.hs configure --prefix=/usr
$ runhaskell Setup.hs build
$ runhaskell Setup.hs copy --destdir=/tmp/mypkg
$ tar -czf mypkg.tar.gz /tmp/mypkg/

If the package contains a library, you need two additional steps:

$ runhaskell Setup.hs register --gen-script
$ runhaskell Setup.hs unregister --gen-script

This creates shell scripts register.sh and unregister.sh, which must also be sent to the target system. After unpacking there, the package must be registered by running the register.sh script. The unregister.sh script would be used in the uninstall procedure of the package. Similar steps may be used for creating binary packages for Windows.

The following options are understood by all commands:

--help, -h or -?

List the available options for the command.

--verbose=n or -v n

Set the verbosity level (0-3). The normal level is 1; a missing n defaults to 2.

There is also an extended version of this command which can be used to fine-tune the verbosity of output. It takes the form [silent|normal|verbose|debug]flags, where flags is a list of + flags which toggle various aspects of output. At the moment, only +callsite and +callstack are supported, which respectively toggle call site and call stack printing (these are only supported if Cabal is built with a sufficiently recent GHC.)

The various commands and the additional options they support are described below. In the simple build infrastructure, any other options will be reported as errors.

setup configure

Prepare to build the package. Typically, this step checks that the target platform is capable of building the package, and discovers platform-specific features that are needed during the build.

The user may also adjust the behaviour of later stages using the options listed in the following subsections. In the simple build infrastructure, the values supplied via these options are recorded in a private file read by later stages.

If a user-supplied configure script is run (see the section on system-dependent parameters or on complex packages), it is passed the --with-hc-pkg, --prefix, --bindir, --libdir, --dynlibdir, --datadir, --libexecdir and --sysconfdir options. In addition the value of the --with-compiler option is passed in a --with-hc-pkg option and all options specified with --configure-option are passed on.

In Cabal 2.0, support for a single positional argument was added to setup configure This makes Cabal configure a the specific component to be configured. Specified names can be qualified with lib: or exe: in case just a name is ambiguous (as would be the case for a package named p which has a library and an executable named p.) This has the following effects:

  • Subsequent invocations of cabal build, register, etc. operate only on the configured component.
  • Cabal requires all “internal” dependencies (e.g., an executable depending on a library defined in the same package) must be found in the set of databases via --package-db (and related flags): these dependencies are assumed to be up-to-date. A dependency can be explicitly specified using --dependency simply by giving the name of the internal library; e.g., the dependency for an internal library named foo is given as --dependency=pkg-internal=pkg-1.0-internal-abcd.
  • Only the dependencies needed for the requested component are required. Similarly, when --exact-configuration is specified, it’s only necessary to specify --dependency for the component. (As mentioned previously, you must specify internal dependencies as well.)
  • Internal build-tool-depends and build-tools dependencies are expected to be in the PATH upon subsequent invocations of setup.

Full details can be found in the Componentized Cabal proposal.

Programs used for building

The following options govern the programs used to process the source files of a package:

--ghc or -g, --jhc, --lhc, --uhc

Specify which Haskell implementation to use to build the package. At most one of these flags may be given. If none is given, the implementation under which the setup script was compiled or interpreted is used.

--with-compiler=path or -w *path*

Specify the path to a particular compiler. If given, this must match the implementation selected above. The default is to search for the usual name of the selected implementation.

This flag also sets the default value of the --with-hc-pkg option to the package tool for this compiler. Check the output of setup configure -v to ensure that it finds the right package tool (or use --with-hc-pkg explicitly).

--with-hc-pkg=path

Specify the path to the package tool, e.g. ghc-pkg. The package tool must be compatible with the compiler specified by --with-compiler. If this option is omitted, the default value is determined from the compiler selected.

--with-prog=path

Specify the path to the program prog. Any program known to Cabal can be used in place of prog. It can either be a fully path or the name of a program that can be found on the program search path. For example: --with-ghc=ghc-6.6.1 or --with-cpphs=/usr/local/bin/cpphs. The full list of accepted programs is not enumerated in this user guide. Rather, run cabal install --help to view the list.

--prog-options=options

Specify additional options to the program prog. Any program known to Cabal can be used in place of prog. For example: --alex-options="--template=mytemplatedir/". The options is split into program options based on spaces. Any options containing embedded spaced need to be quoted, for example --foo-options='--bar="C:\Program File\Bar"'. As an alternative that takes only one option at a time but avoids the need to quote, use --prog-option instead.

--prog-option=option

Specify a single additional option to the program prog. For passing an option that contain embedded spaces, such as a file name with embedded spaces, using this rather than --prog-options means you do not need an additional level of quoting. Of course if you are using a command shell you may still need to quote, for example --foo-options="--bar=C:\Program File\Bar".

All of the options passed with either --prog-options or --prog-option are passed in the order they were specified on the configure command line.

Installation paths

The following options govern the location of installed files from a package:

--prefix=dir

The root of the installation. For example for a global install you might use /usr/local on a Unix system, or C:\Program Files on a Windows system. The other installation paths are usually subdirectories of prefix, but they don’t have to be.

In the simple build system, dir may contain the following path variables: $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--bindir=dir

Executables that the user might invoke are installed here.

In the simple build system, dir may contain the following path variables: $prefix, $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--libdir=dir

Object-code libraries are installed here.

In the simple build system, dir may contain the following path variables: $prefix, $bindir, $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--dynlibdir=dir

Dynamic libraries are installed here.

By default, this is set to $libdir/$abi, which is usually not equal to $libdir/$libsubdir.

In the simple build system, dir may contain the following path variables: $prefix, $bindir, $libdir, $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--libexecdir=dir

Executables that are not expected to be invoked directly by the user are installed here.

In the simple build system, dir may contain the following path variables: $prefix, $bindir, $libdir, $libsubdir, $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--datadir=dir

Architecture-independent data files are installed here.

In the simple build system, dir may contain the following path variables: $prefix, $bindir, $libdir, $libsubdir, $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--sysconfdir=dir

Installation directory for the configuration files.

In the simple build system, dir may contain the following path variables: $prefix, $bindir, $libdir, $libsubdir, $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

In addition the simple build system supports the following installation path options:

--libsubdir=dir

A subdirectory of libdir in which libraries are actually installed. For example, in the simple build system on Unix, the default libdir is /usr/local/lib, and libsubdir contains the compiler ABI and package identifier, e.g. x86_64-linux-ghc-8.0.2/mypkg-0.1.0-IxQNmCA7qrSEQNkoHSF7A, so libraries would be installed in /usr/local/lib/x86_64-linux-ghc-8.0.2/mypkg-0.1.0-IxQNmCA7qrSEQNkoHSF7A/.

dir may contain the following path variables: $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--libexecsubdir=dir

A subdirectory of libexecdir in which private executables are installed. For example, in the simple build system on Unix, the default libexecdir is /usr/local/libexec, and libsubdir is x86_64-linux-ghc-8.0.2/mypkg-0.1.0, so private executables would be installed in /usr/local/libexec/x86_64-linux-ghc-8.0.2/mypkg-0.1.0/

dir may contain the following path variables: $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--datasubdir=dir

A subdirectory of datadir in which data files are actually installed.

dir may contain the following path variables: $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--docdir=dir

Documentation files are installed relative to this directory.

dir may contain the following path variables: $prefix, $bindir, $libdir, $libsubdir, $datadir, $datasubdir, $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--htmldir=dir

HTML documentation files are installed relative to this directory.

dir may contain the following path variables: $prefix, $bindir, $libdir, $libsubdir, $datadir, $datasubdir, $docdir, $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--program-prefix=prefix

Prepend prefix to installed program names.

prefix may contain the following path variables: $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

--program-suffix=suffix

Append suffix to installed program names. The most obvious use for this is to append the program’s version number to make it possible to install several versions of a program at once: --program-suffix='$version'.

suffix may contain the following path variables: $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

Path variables in the simple build system

For the simple build system, there are a number of variables that can be used when specifying installation paths. The defaults are also specified in terms of these variables. A number of the variables are actually for other paths, like $prefix. This allows paths to be specified relative to each other rather than as absolute paths, which is important for building relocatable packages (see prefix independence).

$prefix
The path variable that stands for the root of the installation. For an installation to be relocatable, all other installation paths must be relative to the $prefix variable.
$bindir
The path variable that expands to the path given by the --bindir configure option (or the default).
$libdir
As above but for --libdir
$libsubdir
As above but for --libsubdir
$dynlibdir
As above but for --dynlibdir
$datadir
As above but for --datadir
$datasubdir
As above but for --datasubdir
$docdir
As above but for --docdir
$pkgid
The name and version of the package, e.g. mypkg-0.2
$pkg
The name of the package, e.g. mypkg
$version
The version of the package, e.g. 0.2
$compiler
The compiler being used to build the package, e.g. ghc-6.6.1
$os
The operating system of the computer being used to build the package, e.g. linux, windows, osx, freebsd or solaris
$arch
The architecture of the computer being used to build the package, e.g. i386, x86_64, ppc or sparc
$abitag
An optional tag that a compiler can use for telling incompatible ABI’s on the same architecture apart. GHCJS encodes the underlying GHC version in the ABI tag.
$abi
A shortcut for getting a path that completely identifies the platform in terms of binary compatibility. Expands to the same value as $arch-$os-compiler-$abitag if the compiler uses an abi tag, $arch-$os-$compiler if it doesn’t.
Paths in the simple build system

For the simple build system, the following defaults apply:

Default installation paths
Option Unix Default Windows Default
--prefix (global) /usr/local %PROGRAMFILES%\Haskell
--prefix (per-user) $HOME/.cabal %APPDATA%\cabal
--bindir $prefix/bin $prefix\bin
--libdir $prefix/lib $prefix
--libsubdir (others) $pkgid/$compiler $pkgid\$compiler
--dynlibdir $libdir/$abi $libdir\$abi
--libexecdir $prefix/libexec $prefix\$pkgid
--datadir (executable) $prefix/share $prefix
--datadir (library) $prefix/share %PROGRAMFILES%\Haskell
--datasubdir $pkgid $pkgid
--docdir $datadir/doc/$pkgid $prefix\doc\$pkgid
--sysconfdir $prefix/etc $prefix\etc
--htmldir $docdir/html $docdir\html
--program-prefix (empty) (empty)
--program-suffix (empty) (empty)
Prefix-independence

On Windows it is possible to obtain the pathname of the running program. This means that we can construct an installable executable package that is independent of its absolute install location. The executable can find its auxiliary files by finding its own path and knowing the location of the other files relative to $bindir. Prefix-independence is particularly useful: it means the user can choose the install location (i.e. the value of $prefix) at install-time, rather than having to bake the path into the binary when it is built.

In order to achieve this, we require that for an executable on Windows, all of $bindir, $libdir, $dynlibdir, $datadir and $libexecdir begin with $prefix. If this is not the case then the compiled executable will have baked-in all absolute paths.

The application need do nothing special to achieve prefix-independence. If it finds any files using getDataFileName and the other functions provided for the purpose, the files will be accessed relative to the location of the current executable.

A library cannot (currently) be prefix-independent, because it will be linked into an executable whose file system location bears no relation to the library package.

Controlling Flag Assignments

Flag assignments (see the resolution of conditions and flags) can be controlled with the following command line options.

-f flagname or -f -flagname

Force the specified flag to true or false (if preceded with a -). Later specifications for the same flags will override earlier, i.e., specifying -fdebug -f-debug is equivalent to -f-debug

--flags=flagspecs

Same as -f, but allows specifying multiple flag assignments at once. The parameter is a space-separated list of flag names (to force a flag to true), optionally preceded by a - (to force a flag to false). For example, --flags="debug -feature1 feature2" is equivalent to -fdebug -f-feature1 -ffeature2.

Building Test Suites
--enable-tests

Build the test suites defined in the package description file during the build stage. Check for dependencies required by the test suites. If the package is configured with this option, it will be possible to run the test suites with the test command after the package is built.

--disable-tests

(default) Do not build any test suites during the build stage. Do not check for dependencies required only by the test suites. It will not be possible to invoke the test command without reconfiguring the package.

--enable-coverage

Build libraries and executables (including test suites) with Haskell Program Coverage enabled. Running the test suites will automatically generate coverage reports with HPC.

--disable-coverage

(default) Do not enable Haskell Program Coverage.

Miscellaneous options
--user

Does a per-user installation. This changes the default installation prefix. It also allow dependencies to be satisfied by the user’s package database, in addition to the global database. This also implies a default of --user for any subsequent install command, as packages registered in the global database should not depend on packages registered in a user’s database.

--global

(default) Does a global installation. In this case package dependencies must be satisfied by the global package database. All packages in the user’s package database will be ignored. Typically the final installation step will require administrative privileges.

--package-db=db

Allows package dependencies to be satisfied from this additional package database db in addition to the global package database. All packages in the user’s package database will be ignored. The interpretation of db is implementation-specific. Typically it will be a file or directory. Not all implementations support arbitrary package databases.

This pushes an extra db onto the db stack. The --global and --user mode switches add the respective [Global] and [Global, User] dbs to the initial stack. There is a compiler-implementation constraint that the global db must appear first in the stack, and if the user one appears at all, it must appear immediately after the global db.

To reset the stack, use --package-db=clear.

--ipid=ipid

Specifies the installed package identifier of the package to be built; this identifier is passed on to GHC and serves as the basis for linker symbols and the id field in a ghc-pkg registration. When a package has multiple components, the actual component identifiers are derived off of this identifier (e.g., an internal library foo from package p-0.1-abcd will get the identifier p-0.1-abcd-foo.

--cid=cid

Specifies the component identifier of the component being built; this is only valid if you are configuring a single component.

--default-user-config=file

Allows a “default” cabal.config freeze file to be passed in manually. This file will only be used if one does not exist in the project directory already. Typically, this can be set from the global cabal config file so as to provide a default set of partial constraints to be used by projects, providing a way for users to peg themselves to stable package collections.

--enable-optimization[=n] or -O [n]

(default) Build with optimization flags (if available). This is appropriate for production use, taking more time to build faster libraries and programs.

The optional n value is the optimisation level. Some compilers support multiple optimisation levels. The range is 0 to 2. Level 0 is equivalent to --disable-optimization, level 1 is the default if no n parameter is given. Level 2 is higher optimisation if the compiler supports it. Level 2 is likely to lead to longer compile times and bigger generated code.

--disable-optimization

Build without optimization. This is suited for development: building will be quicker, but the resulting library or programs will be slower.

--enable-profiling

Build libraries and executables with profiling enabled (for compilers that support profiling as a separate mode). For this to work, all libraries used by this package must also have been built with profiling support. For libraries this involves building an additional instance of the library in addition to the normal non-profiling instance. For executables it changes the single executable to be built in profiling mode.

This flag covers both libraries and executables, but can be overridden by the --enable-library-profiling flag.

See also the --profiling-detail flag below.

--disable-profiling

(default) Do not enable profiling in generated libraries and executables.

--enable-library-profiling or -p

As with --enable-profiling above, but it applies only for libraries. So this generates an additional profiling instance of the library in addition to the normal non-profiling instance.

The --enable-profiling flag controls the profiling mode for both libraries and executables, but if different modes are desired for libraries versus executables then use --enable-library-profiling as well.

--disable-library-profiling

(default) Do not generate an additional profiling version of the library.

--profiling-detail[=level]

Some compilers that support profiling, notably GHC, can allocate costs to different parts of the program and there are different levels of granularity or detail with which this can be done. In particular for GHC this concept is called “cost centers”, and GHC can automatically add cost centers, and can do so in different ways.

This flag covers both libraries and executables, but can be overridden by the --library-profiling-detail flag.

Currently this setting is ignored for compilers other than GHC. The levels that cabal currently supports are:

default
For GHC this uses exported-functions for libraries and toplevel-functions for executables.
none
No costs will be assigned to any code within this component.
exported-functions
Costs will be assigned at the granularity of all top level functions exported from each module. In GHC specifically, this is for non-inline functions.
toplevel-functions
Costs will be assigned at the granularity of all top level functions in each module, whether they are exported from the module or not. In GHC specifically, this is for non-inline functions.
all-functions
Costs will be assigned at the granularity of all functions in each module, whether top level or local. In GHC specifically, this is for non-inline toplevel or where-bound functions or values.

This flag is new in Cabal-1.24. Prior versions used the equivalent of none above.

--library-profiling-detail[=level]

As with --profiling-detail above, but it applies only for libraries.

The level for both libraries and executables is set by the --profiling-detail flag, but if different levels are desired for libraries versus executables then use --library-profiling-detail as well.

--enable-library-vanilla

(default) Build ordinary libraries (as opposed to profiling libraries). This is independent of the --enable-library-profiling option. If you enable both, you get both.

--disable-library-vanilla

Do not build ordinary libraries. This is useful in conjunction with --enable-library-profiling to build only profiling libraries, rather than profiling and ordinary libraries.

--enable-library-for-ghci

(default) Build libraries suitable for use with GHCi.

--disable-library-for-ghci

Not all platforms support GHCi and indeed on some platforms, trying to build GHCi libs fails. In such cases this flag can be used as a workaround.

--enable-split-objs

Use the GHC -split-objs feature when building the library. This reduces the final size of the executables that use the library by allowing them to link with only the bits that they use rather than the entire library. The downside is that building the library takes longer and uses considerably more memory.

--disable-split-objs

(default) Do not use the GHC -split-objs feature. This makes building the library quicker but the final executables that use the library will be larger.

--enable-executable-stripping

(default) When installing binary executable programs, run the strip program on the binary. This can considerably reduce the size of the executable binary file. It does this by removing debugging information and symbols. While such extra information is useful for debugging C programs with traditional debuggers it is rarely helpful for debugging binaries produced by Haskell compilers.

Not all Haskell implementations generate native binaries. For such implementations this option has no effect.

--disable-executable-stripping

Do not strip binary executables during installation. You might want to use this option if you need to debug a program using gdb, for example if you want to debug the C parts of a program containing both Haskell and C code. Another reason is if your are building a package for a system which has a policy of managing the stripping itself (such as some Linux distributions).

--enable-shared

Build shared library. This implies a separate compiler run to generate position independent code as required on most platforms.

--disable-shared

(default) Do not build shared library.

--enable-executable-dynamic

Link executables dynamically. The executable’s library dependencies should be built as shared objects. This implies --enable-shared unless --disable-shared is explicitly specified.

--disable-executable-dynamic

(default) Link executables statically.

--configure-option=str

An extra option to an external configure script, if one is used (see the section on system-dependent parameters). There can be several of these options.

--extra-include-dirs[=dir]

An extra directory to search for C header files. You can use this flag multiple times to get a list of directories.

You might need to use this flag if you have standard system header files in a non-standard location that is not mentioned in the package’s .cabal file. Using this option has the same affect as appending the directory dir to the include-dirs field in each library and executable in the package’s .cabal file. The advantage of course is that you do not have to modify the package at all. These extra directories will be used while building the package and for libraries it is also saved in the package registration information and used when compiling modules that use the library.

--extra-lib-dirs[=dir]

An extra directory to search for system libraries files. You can use this flag multiple times to get a list of directories.

--extra-framework-dirs[=dir]

An extra directory to search for frameworks (OS X only). You can use this flag multiple times to get a list of directories.

You might need to use this flag if you have standard system libraries in a non-standard location that is not mentioned in the package’s .cabal file. Using this option has the same affect as appending the directory dir to the extra-lib-dirs field in each library and executable in the package’s .cabal file. The advantage of course is that you do not have to modify the package at all. These extra directories will be used while building the package and for libraries it is also saved in the package registration information and used when compiling modules that use the library.

--dependency[=pkgname=ipid]

Specify that a particular dependency should used for a particular package name. In particular, it declares that any reference to pkgname in a build-depends should be resolved to ipid.

--exact-configuration

This changes Cabal to require every dependency be explicitly specified using --dependency, rather than use Cabal’s (very simple) dependency solver. This is useful for programmatic use of Cabal’s API, where you want to error if you didn’t specify enough --dependency flags.

--allow-newer[=pkgs], --allow-older[=pkgs]

Selectively relax upper or lower bounds in dependencies without editing the package description respectively.

The following description focuses on upper bounds and the --allow-newer flag, but applies analogously to --allow-older and lower bounds. --allow-newer and --allow-older can be used at the same time.

If you want to install a package A that depends on B >= 1.0 && < 2.0, but you have the version 2.0 of B installed, you can compile A against B 2.0 by using cabal install --allow-newer=B A. This works for the whole package index: if A also depends on C that in turn depends on B < 2.0, C’s dependency on B will be also relaxed.

Example:

$ cd foo
$ cabal configure
Resolving dependencies...
cabal: Could not resolve dependencies:
[...]
$ cabal configure --allow-newer
Resolving dependencies...
Configuring foo...

Additional examples:

# Relax upper bounds in all dependencies.
$ cabal install --allow-newer foo

# Relax upper bounds only in dependencies on bar, baz and quux.
$ cabal install --allow-newer=bar,baz,quux foo

# Relax the upper bound on bar and force bar==2.1.
$ cabal install --allow-newer=bar --constraint="bar==2.1" foo

It’s also possible to limit the scope of --allow-newer to single packages with the --allow-newer=scope:dep syntax. This means that the dependency on dep will be relaxed only for the package scope.

Example:

# Relax upper bound in foo's dependency on base; also relax upper bound in
# every package's dependency on lens.
$ cabal install --allow-newer=foo:base,lens

# Relax upper bounds in foo's dependency on base and bar's dependency
# on time; also relax the upper bound in the dependency on lens specified by
# any package.
$ cabal install --allow-newer=foo:base,lens --allow-newer=bar:time

Finally, one can enable --allow-newer permanently by setting allow-newer: True in the ~/.cabal/config file. Enabling ‘allow-newer’ selectively is also supported in the config file (allow-newer: foo, bar, baz:base).

--constraint=constraint

Restrict solutions involving a package to given version bounds, flag settings, and other properties. For example, to consider only install plans that use version 2.1 of bar or do not use bar at all, write:

$ cabal install --constraint="bar == 2.1"

Version bounds have the same syntax as build-depends. As a special case, the following prevents bar from being used at all:

# Note: this is just syntax sugar for '> 1 && < 1', and is
# supported by build-depends.
$ cabal install --constraint="bar -none"

You can also specify flag assignments:

# Require bar to be installed with the foo flag turned on and
# the baz flag turned off.
$ cabal install --constraint="bar +foo -baz"

To specify multiple constraints, you may pass the constraint option multiple times.

There are also some more specialized constraints, which most people don’t generally need:

# Require that a version of bar be used that is already installed in
# the global package database.
$ cabal install --constraint="bar installed"

# Require the local source copy of bar to be used.
# (Note: By default, if we have a local package we will
# automatically use it, so it will generally not be necessary to
# specify this.)
$ cabal install --constraint="bar source"

# Require that bar have test suites and benchmarks enabled.
$ cabal install --constraint="bar test" --constraint="bar bench"

By default, constraints only apply to build dependencies (build-depends), build dependencies of build dependencies, and so on. Constraints normally do not apply to dependencies of the Setup.hs script of any package (setup-depends) nor do they apply to build tools (build-tool-depends) or the dependencies of build tools. To explicitly apply a constraint to a setup or build tool dependency, you can add a qualifier to the constraint as follows:

# Example use of the 'any' qualifier. This constraint
# applies to package bar anywhere in the dependency graph.
$ cabal install --constraint="any.bar == 1.0"
# Example uses of 'setup' qualifiers.

# This constraint applies to package bar when it is a
# dependency of any Setup.hs script.
$ cabal install --constraint="setup.bar == 1.0"

# This constraint applies to package bar when it is a
# dependency of the Setup.hs script of package foo.
$ cabal install --constraint="foo:setup.bar == 1.0"
--preference=preference

Specify a soft constraint on versions of a package. The solver will attempt to satisfy these preferences on a “best-effort” basis.

setup build

Perform any preprocessing or compilation needed to make this package ready for installation.

This command takes the following options:

--prog-options=options, --prog-option=option

These are mostly the same as the options configure step. Unlike the options specified at the configure step, any program options specified at the build step are not persistent but are used for that invocation only. They options specified at the build step are in addition not in replacement of any options specified at the configure step.

setup haddock

Build the documentation for the package using Haddock. By default, only the documentation for the exposed modules is generated (but see the --executables and --internal flags below).

This command takes the following options:

--hoogle

Generate a file dist/doc/html/pkgid.txt, which can be converted by Hoogle into a database for searching. This is equivalent to running Haddock with the --hoogle flag.

--html-location=url

Specify a template for the location of HTML documentation for prerequisite packages. The substitutions (see listing) are applied to the template to obtain a location for each package, which will be used by hyperlinks in the generated documentation. For example, the following command generates links pointing at Hackage pages:

Here the argument is quoted to prevent substitution by the shell. If this option is omitted, the location for each package is obtained using the package tool (e.g. ghc-pkg).

--executables

Also run Haddock for the modules of all the executable programs. By default Haddock is run only on the exported modules.

--internal

Run Haddock for the all modules, including unexposed ones, and make Haddock generate documentation for unexported symbols as well.

--css=path

The argument path denotes a CSS file, which is passed to Haddock and used to set the style of the generated documentation. This is only needed to override the default style that Haddock uses.

Generate Haddock documentation integrated with HsColour . First, HsColour is run to generate colourised code. Then Haddock is run to generate HTML documentation. Each entity shown in the documentation is linked to its definition in the colourised code.

--hscolour-css=path

The argument path denotes a CSS file, which is passed to HsColour as in

runhaskell Setup.hs hscolour –css=*path*

setup hscolour

Produce colourised code in HTML format using HsColour. Colourised code for exported modules is put in dist/doc/html/pkgid/src.

This command takes the following options:

--executables

Also run HsColour on the sources of all executable programs. Colourised code is put in dist/doc/html/pkgid/executable/src.

--css=path

Use the given CSS file for the generated HTML files. The CSS file defines the colours used to colourise code. Note that this copies the given CSS file to the directory with the generated HTML files (renamed to hscolour.css) rather than linking to it.

setup install

Copy the files into the install locations and (for library packages) register the package with the compiler, i.e. make the modules it contains available to programs.

The install locations are determined by options to setup configure.

This command takes the following options:

--global

Register this package in the system-wide database. (This is the default, unless the setup configure --user option was supplied to the configure command.)

--user

Register this package in the user’s local package database. (This is the default if the setup configure --user option was supplied to the configure command.)

setup copy

Copy the files without registering them. This command is mainly of use to those creating binary packages.

This command takes the following option:

--destdir=path

Specify the directory under which to place installed files. If this is not given, then the root directory is assumed.

setup register

Register this package with the compiler, i.e. make the modules it contains available to programs. This only makes sense for library packages. Note that the install command incorporates this action. The main use of this separate command is in the post-installation step for a binary package.

This command takes the following options:

--global

Register this package in the system-wide database. (This is the default.)

--user

Register this package in the user’s local package database.

--gen-script

Instead of registering the package, generate a script containing commands to perform the registration. On Unix, this file is called register.sh, on Windows, register.bat. This script might be included in a binary bundle, to be run after the bundle is unpacked on the target system.

--gen-pkg-config[=path]

Instead of registering the package, generate a package registration file (or directory, in some circumstances). This only applies to compilers that support package registration files which at the moment is only GHC. The file should be used with the compiler’s mechanism for registering packages. This option is mainly intended for packaging systems. If possible use the --gen-script option instead since it is more portable across Haskell implementations. The path is optional and can be used to specify a particular output file to generate. Otherwise, by default the file is the package name and version with a .conf extension.

This option outputs a directory if the package requires multiple registrations: this can occur if internal/convenience libraries are used. These configuration file names are sorted so that they can be registered in order.

--inplace

Registers the package for use directly from the build tree, without needing to install it. This can be useful for testing: there’s no need to install the package after modifying it, just recompile and test.

This flag does not create a build-tree-local package database. It still registers the package in one of the user or global databases.

However, there are some caveats. It only works with GHC (currently). It only works if your package doesn’t depend on having any supplemental files installed — plain Haskell libraries should be fine.

setup unregister

Deregister this package with the compiler.

This command takes the following options:

--global

Deregister this package in the system-wide database. (This is the default.)

--user

Deregister this package in the user’s local package database.

--gen-script

Instead of deregistering the package, generate a script containing commands to perform the deregistration. On Unix, this file is called unregister.sh, on Windows, unregister.bat. This script might be included in a binary bundle, to be run on the target system.

setup clean

Remove any local files created during the configure, build, haddock, register or unregister steps, and also any files and directories listed in the extra-tmp-files field.

This command takes the following options:

--save-configure, -s

Keeps the configuration information so it is not necessary to run the configure step again before building.

setup test

Run the test suites specified in the package description file. Aside from the following flags, Cabal accepts the name of one or more test suites on the command line after test. When supplied, Cabal will run only the named test suites, otherwise, Cabal will run all test suites in the package.

--builddir=dir

The directory where Cabal puts generated build files (default: dist). Test logs will be located in the test subdirectory.

--human-log=path

The template used to name human-readable test logs; the path is relative to dist/test. By default, logs are named according to the template $pkgid-$test-suite.log, so that each test suite will be logged to its own human-readable log file. Template variables allowed are: $pkgid, $compiler, $os, $arch, $abi, $abitag, $test-suite, and $result.

--machine-log=path

The path to the machine-readable log, relative to dist/test. The default template is $pkgid.log. Template variables allowed are: $pkgid, $compiler, $os, $arch, $abi, $abitag and $result.

--show-details=filter

Determines if the results of individual test cases are shown on the terminal. May be always (always show), never (never show), failures (show only failed results), or streaming (show all results in real time).

--test-options=options
Give extra options to the test executables.
--test-option=option

give an extra option to the test executables. There is no need to quote options containing spaces because a single option is assumed, so options will not be split on spaces.

setup sdist

Create a system- and compiler-independent source distribution in a file package-version.tar.gz in the dist subdirectory, for distribution to package builders. When unpacked, the commands listed in this section will be available.

The files placed in this distribution are the package description file, the setup script, the sources of the modules named in the package description file, and files named in the license-file, main-is, c-sources, js-sources, data-files, extra-source-files and extra-doc-files fields.

This command takes the following option:

--snapshot

Append today’s date (in “YYYYMMDD” format) to the version number for the generated source package. The original package is unaffected.

Package Concepts and Development

Quickstart

Lets assume we have created a project directory and already have a Haskell module or two.

Every project needs a name, we’ll call this example “proglet”.

$ cd proglet/
$ ls
Proglet.hs

It is assumed that (apart from external dependencies) all the files that make up a package live under a common project root directory. This simple example has all the project files in one directory, but most packages will use one or more subdirectories.

To turn this into a Cabal package we need two extra files in the project’s root directory:

  • proglet.cabal: containing package metadata and build information.
  • Setup.hs: usually containing a few standardized lines of code, but can be customized if necessary.

We can create both files manually or we can use cabal init to create them for us.

Using “cabal init”

The cabal init command is interactive. It asks us a number of questions starting with the package name and version.

$ cabal init
Package name [default "proglet"]?
Package version [default "0.1"]?
...

It also asks questions about various other bits of package metadata. For a package that you never intend to distribute to others, these fields can be left blank.

One of the important questions is whether the package contains a library or an executable. Libraries are collections of Haskell modules that can be re-used by other Haskell libraries and programs, while executables are standalone programs.

What does the package build:
   1) Library
   2) Executable
Your choice?

For the moment these are the only choices. For more complex packages (e.g. a library and multiple executables or test suites) the .cabal file can be edited afterwards.

Finally, cabal init creates the initial proglet.cabal and Setup.hs files, and depending on your choice of license, a LICENSE file as well.

Generating LICENSE...
Generating Setup.hs...
Generating proglet.cabal...

You may want to edit the .cabal file and add a Description field.

As this stage the proglet.cabal is not quite complete and before you are able to build the package you will need to edit the file and add some build information about the library or executable.

Editing the .cabal file

Load up the .cabal file in a text editor. The first part of the .cabal file has the package metadata and towards the end of the file you will find the executable or library section.

You will see that the fields that have yet to be filled in are commented out. Cabal files use “--” Haskell-style comment syntax. (Note that comments are only allowed on lines on their own. Trailing comments on other lines are not allowed because they could be confused with program options.)

If you selected earlier to create a library package then your .cabal file will have a section that looks like this:

library
  exposed-modules:     Proglet
  -- other-modules:
  -- build-depends:

Alternatively, if you selected an executable then there will be a section like:

executable proglet
  -- main-is:
  -- other-modules:
  -- build-depends:

The build information fields listed (but commented out) are just the few most important and common fields. There are many others that are covered later in this chapter.

Most of the build information fields are the same between libraries and executables. The difference is that libraries have a number of “exposed” modules that make up the public interface of the library, while executables have a file containing a Main module.

The name of a library always matches the name of the package, so it is not specified in the library section. Executables often follow the name of the package too, but this is not required and the name is given explicitly.

Modules included in the package

For a library, cabal init looks in the project directory for files that look like Haskell modules and adds all the modules to the library:exposed-modules field. For modules that do not form part of your package’s public interface, you can move those modules to the other-modules field. Either way, all modules in the library need to be listed.

For an executable, cabal init does not try to guess which file contains your program’s Main module. You will need to fill in the executable:main-is field with the file name of your program’s Main module (including .hs or .lhs extension). Other modules included in the executable should be listed in the other-modules field.

Modules imported from other packages

While your library or executable may include a number of modules, it almost certainly also imports a number of external modules from the standard libraries or other pre-packaged libraries. (These other libraries are of course just Cabal packages that contain a library.)

You have to list all of the library packages that your library or executable imports modules from. Or to put it another way: you have to list all the other packages that your package depends on.

For example, suppose the example Proglet module imports the module Data.Map. The Data.Map module comes from the containers package, so we must list it:

library
  exposed-modules:     Proglet
  other-modules:
  build-depends:       containers, base == 4.*

In addition, almost every package also depends on the base library package because it exports the standard Prelude module plus other basic modules like Data.List.

You will notice that we have listed base == 4.*. This gives a constraint on the version of the base package that our package will work with. The most common kinds of constraints are:

  • pkgname >= n
  • pkgname >= n && < m
  • pkgname == n.*

The last is just shorthand, for example base == 4.* means exactly the same thing as base >= 4 && < 5.

Building the package

For simple packages that’s it! We can now try configuring and building the package:

$ cabal configure
$ cabal build

Assuming those two steps worked then you can also install the package:

$ cabal install

For libraries this makes them available for use in GHCi or to be used by other packages. For executables it installs the program so that you can run it (though you may first need to adjust your system’s $PATH).

Next steps

What we have covered so far should be enough for very simple packages that you use on your own system.

The next few sections cover more details needed for more complex packages and details needed for distributing packages to other people.

The previous chapter covers building and installing packages – your own packages or ones developed by other people.

Package concepts

Before diving into the details of writing packages it helps to understand a bit about packages in the Haskell world and the particular approach that Cabal takes.

The point of packages

Packages are a mechanism for organising and distributing code. Packages are particularly suited for “programming in the large”, that is building big systems by using and re-using code written by different people at different times.

People organise code into packages based on functionality and dependencies. Social factors are also important: most packages have a single author, or a relatively small team of authors.

Packages are also used for distribution: the idea is that a package can be created in one place and be moved to a different computer and be usable in that different environment. There are a surprising number of details that have to be got right for this to work, and a good package system helps to simply this process and make it reliable.

Packages come in two main flavours: libraries of reusable code, and complete programs. Libraries present a code interface, an API, while programs can be run directly. In the Haskell world, library packages expose a set of Haskell modules as their public interface. Cabal packages can contain a library or executables or both.

Some programming languages have packages as a builtin language concept. For example in Java, a package provides a local namespace for types and other definitions. In the Haskell world, packages are not a part of the language itself. Haskell programs consist of a number of modules, and packages just provide a way to partition the modules into sets of related functionality. Thus the choice of module names in Haskell is still important, even when using packages.

Package names and versions

All packages have a name, e.g. “HUnit”. Package names are assumed to be unique. Cabal package names may contain letters, numbers and hyphens, but not spaces and may also not contain a hyphened section consisting of only numbers. The namespace for Cabal packages is flat, not hierarchical.

Packages also have a version, e.g “1.1”. This matches the typical way in which packages are developed. Strictly speaking, each version of a package is independent, but usually they are very similar. Cabal package versions follow the conventional numeric style, consisting of a sequence of digits such as “1.0.1” or “2.0”. There are a range of common conventions for “versioning” packages, that is giving some meaning to the version number in terms of changes in the package. Section [TODO] has some tips on package versioning.

The combination of package name and version is called the package ID and is written with a hyphen to separate the name and version, e.g. “HUnit-1.1”.

For Cabal packages, the combination of the package name and version uniquely identifies each package. Or to put it another way: two packages with the same name and version are considered to be the same.

Strictly speaking, the package ID only identifies each Cabal source package; the same Cabal source package can be configured and built in different ways. There is a separate installed package ID that uniquely identifies each installed package instance. Most of the time however, users need not be aware of this detail.

Kinds of package: Cabal vs GHC vs system

It can be slightly confusing at first because there are various different notions of package floating around. Fortunately the details are not very complicated.

Cabal packages

Cabal packages are really source packages. That is they contain Haskell (and sometimes C) source code.

Cabal packages can be compiled to produce GHC packages. They can also be translated into operating system packages.

GHC packages

This is GHC’s view on packages. GHC only cares about library packages, not executables. Library packages have to be registered with GHC for them to be available in GHCi or to be used when compiling other programs or packages.

The low-level tool ghc-pkg is used to register GHC packages and to get information on what packages are currently registered.

You never need to make GHC packages manually. When you build and install a Cabal package containing a library then it gets registered with GHC automatically.

Haskell implementations other than GHC have essentially the same concept of registered packages. For the most part, Cabal hides the slight differences.

Operating system packages

On operating systems like Linux and Mac OS X, the system has a specific notion of a package and there are tools for installing and managing packages.

The Cabal package format is designed to allow Cabal packages to be translated, mostly-automatically, into operating system packages. They are usually translated 1:1, that is a single Cabal package becomes a single system package.

It is also possible to make Windows installers from Cabal packages, though this is typically done for a program together with all of its library dependencies, rather than packaging each library separately.

Unit of distribution

The Cabal package is the unit of distribution. What this means is that each Cabal package can be distributed on its own in source or binary form. Of course there may dependencies between packages, but there is usually a degree of flexibility in which versions of packages can work together so distributing them independently makes sense.

It is perhaps easiest to see what being “the unit of distribution” means by contrast to an alternative approach. Many projects are made up of several interdependent packages and during development these might all be kept under one common directory tree and be built and tested together. When it comes to distribution however, rather than distributing them all together in a single tarball, it is required that they each be distributed independently in their own tarballs.

Cabal’s approach is to say that if you can specify a dependency on a package then that package should be able to be distributed independently. Or to put it the other way round, if you want to distribute it as a single unit, then it should be a single package.

Explicit dependencies and automatic package management

Cabal takes the approach that all packages dependencies are specified explicitly and specified in a declarative way. The point is to enable automatic package management. This means tools like cabal can resolve dependencies and install a package plus all of its dependencies automatically. Alternatively, it is possible to mechanically (or mostly mechanically) translate Cabal packages into system packages and let the system package manager install dependencies automatically.

It is important to track dependencies accurately so that packages can reliably be moved from one system to another system and still be able to build it there. Cabal is therefore relatively strict about specifying dependencies. For example Cabal’s default build system will not even let code build if it tries to import a module from a package that isn’t listed in the .cabal file, even if that package is actually installed. This helps to ensure that there are no “untracked dependencies” that could cause the code to fail to build on some other system.

The explicit dependency approach is in contrast to the traditional “./configure” approach where instead of specifying dependencies declaratively, the ./configure script checks if the dependencies are present on the system. Some manual work is required to transform a ./configure based package into a Linux distribution package (or similar). This conversion work is usually done by people other than the package author(s). The practical effect of this is that only the most popular packages will benefit from automatic package management. Instead, Cabal forces the original author to specify the dependencies but the advantage is that every package can benefit from automatic package management.

The “./configure” approach tends to encourage packages that adapt themselves to the environment in which they are built, for example by disabling optional features so that they can continue to work when a particular dependency is not available. This approach makes sense in a world where installing additional dependencies is a tiresome manual process and so minimising dependencies is important. The automatic package management view is that packages should just declare what they need and the package manager will take responsibility for ensuring that all the dependencies are installed.

Sometimes of course optional features and optional dependencies do make sense. Cabal packages can have optional features and varying dependencies. These conditional dependencies are still specified in a declarative way however and remain compatible with automatic package management. The need to remain compatible with automatic package management means that Cabal’s conditional dependencies system is a bit less flexible than with the “./configure” approach.

Portability

One of the purposes of Cabal is to make it easier to build packages on different platforms (operating systems and CPU architectures), with different compiler versions and indeed even with different Haskell implementations. (Yes, there are Haskell implementations other than GHC!)

Cabal provides abstractions of features present in different Haskell implementations and wherever possible it is best to take advantage of these to increase portability. Where necessary however it is possible to use specific features of specific implementations.

For example a package author can list in the package’s .cabal what language extensions the code uses. This allows Cabal to figure out if the language extension is supported by the Haskell implementation that the user picks. Additionally, certain language extensions such as Template Haskell require special handling from the build system and by listing the extension it provides the build system with enough information to do the right thing.

Another similar example is linking with foreign libraries. Rather than specifying GHC flags directly, the package author can list the libraries that are needed and the build system will take care of using the right flags for the compiler. Additionally this makes it easier for tools to discover what system C libraries a package needs, which is useful for tracking dependencies on system libraries (e.g. when translating into Linux distribution packages).

In fact both of these examples fall into the category of explicitly specifying dependencies. Not all dependencies are other Cabal packages. Foreign libraries are clearly another kind of dependency. It’s also possible to think of language extensions as dependencies: the package depends on a Haskell implementation that supports all those extensions.

Where compiler-specific options are needed however, there is an “escape hatch” available. The developer can specify implementation-specific options and more generally there is a configuration mechanism to customise many aspects of how a package is built depending on the Haskell implementation, the operating system, computer architecture and user-specified configuration flags.

Developing packages

The Cabal package is the unit of distribution. When installed, its purpose is to make available:

  • One or more Haskell programs.
  • At most one library, exposing a number of Haskell modules.

However having both a library and executables in a package does not work very well; if the executables depend on the library, they must explicitly list all the modules they directly or indirectly import from that library. Fortunately, starting with Cabal 1.8.0.4, executables can also declare the package that they are in as a dependency, and Cabal will treat them as if they were in another package that depended on the library.

Internally, the package may consist of much more than a bunch of Haskell modules: it may also have C source code and header files, source code meant for preprocessing, documentation, test cases, auxiliary tools etc.

A package is identified by a globally-unique package name, which consists of one or more alphanumeric words separated by hyphens. To avoid ambiguity, each of these words should contain at least one letter. Chaos will result if two distinct packages with the same name are installed on the same system. A particular version of the package is distinguished by a version number, consisting of a sequence of one or more integers separated by dots. These can be combined to form a single text string called the package ID, using a hyphen to separate the name from the version, e.g. “HUnit-1.1”.

Note

Packages are not part of the Haskell language; they simply populate the hierarchical space of module names. In GHC 6.6 and later a program may contain multiple modules with the same name if they come from separate packages; in all other current Haskell systems packages may not overlap in the modules they provide, including hidden modules.

Creating a package

Suppose you have a directory hierarchy containing the source files that make up your package. You will need to add two more files to the root directory of the package:

package.cabal
a Unicode UTF-8 text file containing a package description. For details of the syntax of this file, see the section on package descriptions.
Setup.hs
a single-module Haskell program to perform various setup tasks (with the interface described in the section on Building and installing packages). This module should import only modules that will be present in all Haskell implementations, including modules of the Cabal library. The content of this file is determined by the build-type setting in the .cabal file. In most cases it will be trivial, calling on the Cabal library to do most of the work.

Once you have these, you can create a source bundle of this directory for distribution. Building of the package is discussed in the section on Building and installing packages.

One of the purposes of Cabal is to make it easier to build a package with different Haskell implementations. So it provides abstractions of features present in different Haskell implementations and wherever possible it is best to take advantage of these to increase portability. Where necessary however it is possible to use specific features of specific implementations. For example one of the pieces of information a package author can put in the package’s .cabal file is what language extensions the code uses. This is far preferable to specifying flags for a specific compiler as it allows Cabal to pick the right flags for the Haskell implementation that the user picks. It also allows Cabal to figure out if the language extension is even supported by the Haskell implementation that the user picks. Where compiler-specific options are needed however, there is an “escape hatch” available. The developer can specify implementation-specific options and more generally there is a configuration mechanism to customise many aspects of how a package is built depending on the Haskell implementation, the Operating system, computer architecture and user-specified configuration flags.

name:     Foo
version:  1.0

library
  build-depends:   base
  exposed-modules: Foo
  extensions:      ForeignFunctionInterface
  ghc-options:     -Wall
  if os(windows)
    build-depends: Win32
Example: A package containing a simple library

The HUnit package contains a file HUnit.cabal containing:

name:           HUnit
version:        1.1.1
synopsis:       A unit testing framework for Haskell
homepage:       http://hunit.sourceforge.net/
category:       Testing
author:         Dean Herington
license:        BSD3
license-file:   LICENSE
cabal-version:  >= 1.10
build-type:     Simple

library
  build-depends:      base >= 2 && < 4
  exposed-modules:    Test.HUnit.Base, Test.HUnit.Lang,
                      Test.HUnit.Terminal, Test.HUnit.Text, Test.HUnit
  default-extensions: CPP

and the following Setup.hs:

import Distribution.Simple
main = defaultMain
Example: A package containing executable programs
name:           TestPackage
version:        0.0
synopsis:       Small package with two programs
author:         Angela Author
license:        BSD3
build-type:     Simple
cabal-version:  >= 1.2

executable program1
  build-depends:  HUnit
  main-is:        Main.hs
  hs-source-dirs: prog1

executable program2
  main-is:        Main.hs
  build-depends:  HUnit
  hs-source-dirs: prog2
  other-modules:  Utils

with Setup.hs the same as above.

Example: A package containing a library and executable programs
name:            TestPackage
version:         0.0
synopsis:        Package with library and two programs
license:         BSD3
author:          Angela Author
build-type:      Simple
cabal-version:   >= 1.2

library
  build-depends:   HUnit
  exposed-modules: A, B, C

executable program1
  main-is:         Main.hs
  hs-source-dirs:  prog1
  other-modules:   A, B

executable program2
  main-is:         Main.hs
  hs-source-dirs:  prog2
  other-modules:   A, C, Utils

with Setup.hs the same as above. Note that any library modules required (directly or indirectly) by an executable must be listed again.

The trivial setup script used in these examples uses the simple build infrastructure provided by the Cabal library (see Distribution.Simple). The simplicity lies in its interface rather that its implementation. It automatically handles preprocessing with standard preprocessors, and builds packages for all the Haskell implementations.

The simple build infrastructure can also handle packages where building is governed by system-dependent parameters, if you specify a little more (see the section on system-dependent parameters). A few packages require more elaborate solutions.

Package descriptions

The package description file must have a name ending in “.cabal”. It must be a Unicode text file encoded using valid UTF-8. There must be exactly one such file in the directory. The first part of the name is usually the package name, and some of the tools that operate on Cabal packages require this.

In the package description file, lines whose first non-whitespace characters are “--” are treated as comments and ignored.

This file should contain of a number global property descriptions and several sections.

  • The package properties describe the package as a whole, such as name, license, author, etc.
  • Optionally, a number of configuration flags can be declared. These can be used to enable or disable certain features of a package. (see the section on configurations).
  • The (optional) library section specifies the library properties and relevant build information.
  • Following is an arbitrary number of executable sections which describe an executable program and relevant build information.

Each section consists of a number of property descriptions in the form of field/value pairs, with a syntax roughly like mail message headers.

  • Case is not significant in field names, but is significant in field values.
  • To continue a field value, indent the next line relative to the field name.
  • Field names may be indented, but all field values in the same section must use the same indentation.
  • Tabs are not allowed as indentation characters due to a missing standard interpretation of tab width.
  • To get a blank line in a field value, use an indented “.

The syntax of the value depends on the field. Field types include:

token, filename, directory
Either a sequence of one or more non-space non-comma characters, or a quoted string in Haskell 98 lexical syntax. The latter can be used for escaping whitespace, for example: ghc-options: -Wall "-with-rtsopts=-T -I1". Unless otherwise stated, relative filenames and directories are interpreted from the package root directory.
freeform, URL, address
An arbitrary, uninterpreted string.
identifier
A letter followed by zero or more alphanumerics or underscores.
compiler
A compiler flavor (one of: GHC, JHC, UHC or LHC) followed by a version range. For example, GHC ==6.10.3, or LHC >=0.6 && <0.8.
Modules and preprocessors

Haskell module names listed in the library:exposed-modules and library:other-modules fields may correspond to Haskell source files, i.e. with names ending in “.hs” or “.lhs”, or to inputs for various Haskell preprocessors. The simple build infrastructure understands the extensions:

When building, Cabal will automatically run the appropriate preprocessor and compile the Haskell module it produces. For the c2hs and hsc2hs preprocessors, Cabal will also automatically add, compile and link any C sources generated by the preprocessor (produced by hsc2hs’s #def feature or c2hs’s auto-generated wrapper functions).

Some fields take lists of values, which are optionally separated by commas, except for the build-depends field, where the commas are mandatory.

Some fields are marked as required. All others are optional, and unless otherwise specified have empty default values.

Package properties

These fields may occur in the first top-level properties section and describe the package as a whole:

name: package-name (required)

The unique name of the package, without the version number.

version: numbers (required)

The package version number, usually consisting of a sequence of natural numbers separated by dots.

cabal-version: >= x.y

The version of the Cabal specification that this package description uses. The Cabal specification does slowly evolve, introducing new features and occasionally changing the meaning of existing features. By specifying which version of the spec you are using it enables programs which process the package description to know what syntax to expect and what each part means.

For historical reasons this is always expressed using >= version range syntax. No other kinds of version range make sense, in particular upper bounds do not make sense. In future this field will specify just a version number, rather than a version range.

The version number you specify will affect both compatibility and behaviour. Most tools (including the Cabal library and cabal program) understand a range of versions of the Cabal specification. Older tools will of course only work with older versions of the Cabal specification. Most of the time, tools that are too old will recognise this fact and produce a suitable error message.

As for behaviour, new versions of the Cabal spec can change the meaning of existing syntax. This means if you want to take advantage of the new meaning or behaviour then you must specify the newer Cabal version. Tools are expected to use the meaning and behaviour appropriate to the version given in the package description.

In particular, the syntax of package descriptions changed significantly with Cabal version 1.2 and the cabal-version field is now required. Files written in the old syntax are still recognized, so if you require compatibility with very old Cabal versions then you may write your package description file using the old syntax. Please consult the user’s guide of an older Cabal version for a description of that syntax.

build-type: identifier
Default value:Custom

The type of build used by this package. Build types are the constructors of the BuildType type, defaulting to Custom.

If the build type is anything other than Custom, then the Setup.hs file must be exactly the standardized content discussed below. This is because in these cases, cabal will ignore the Setup.hs file completely, whereas other methods of package management, such as runhaskell Setup.hs [CMD], still rely on the Setup.hs file.

For build type Simple, the contents of Setup.hs must be:

import Distribution.Simple
main = defaultMain

For build type Configure (see the section on system-dependent parameters below), the contents of Setup.hs must be:

import Distribution.Simple
main = defaultMainWithHooks autoconfUserHooks

For build type Make (see the section on more complex packages below), the contents of Setup.hs must be:

import Distribution.Make
main = defaultMain

For build type Custom, the file Setup.hs can be customized, and will be used both by cabal and other tools.

For most packages, the build type Simple is sufficient.

license: identifier
Default value:AllRightsReserved

The type of license under which this package is distributed. License names are the constants of the License type.

license-file: filename
license-files: filename list

The name of a file(s) containing the precise copyright license for this package. The license file(s) will be installed with the package.

If you have multiple license files then use the license-files field instead of (or in addition to) the license-file field.

The content of a copyright notice, typically the name of the holder of the copyright on the package and the year(s) from which copyright is claimed. For example:

copyright: (c) 2006-2007 Joe Bloggs
author: freeform

The original author of the package.

Remember that .cabal files are Unicode, using the UTF-8 encoding.

maintainer: address

The current maintainer or maintainers of the package. This is an e-mail address to which users should send bug reports, feature requests and patches.

stability: freeform

The stability level of the package, e.g. alpha, experimental, provisional, stable.

homepage: URL

The package homepage.

bug-reports: URL

The URL where users should direct bug reports. This would normally be either:

  • A mailto: URL, e.g. for a person or a mailing list.
  • An http: (or https:) URL for an online bug tracking system.

For example Cabal itself uses a web-based bug tracking system

bug-reports: https://github.com/haskell/cabal/issues
package-url: URL

The location of a source bundle for the package. The distribution should be a Cabal package.

synopsis: freeform

A very short description of the package, for use in a table of packages. This is your headline, so keep it short (one line) but as informative as possible. Save space by not including the package name or saying it’s written in Haskell.

description: freeform

Description of the package. This may be several paragraphs, and should be aimed at a Haskell programmer who has never heard of your package before.

For library packages, this field is used as prologue text by setup haddock and thus may contain the same markup as Haddock documentation comments.

category: freeform

A classification category for future use by the package catalogue Hackage. These categories have not yet been specified, but the upper levels of the module hierarchy make a good start.

tested-with: compiler list

A list of compilers and versions against which the package has been tested (or at least built).

data-files: filename list

A list of files to be installed for run-time use by the package. This is useful for packages that use a large amount of static data, such as tables of values or code templates. Cabal provides a way to find these files at run-time.

A limited form of * wildcards in file names, for example data-files: images/*.png matches all the .png files in the images directory.

The limitation is that * wildcards are only allowed in place of the file name, not in the directory name or file extension. In particular, wildcards do not include directories contents recursively. Furthermore, if a wildcard is used it must be used with an extension, so data-files: data/* is not allowed. When matching a wildcard plus extension, a file’s full extension must match exactly, so *.gz matches foo.gz but not foo.tar.gz. A wildcard that does not match any files is an error.

The reason for providing only a very limited form of wildcard is to concisely express the common case of a large number of related files of the same file type without making it too easy to accidentally include unwanted files.

data-dir: directory

The directory where Cabal looks for data files to install, relative to the source directory. By default, Cabal will look in the source directory itself.

extra-source-files: filename list

A list of additional files to be included in source distributions built with setup sdist. As with data-files it can use a limited form of * wildcards in file names.

extra-doc-files: filename list

A list of additional files to be included in source distributions, and also copied to the html directory when Haddock documentation is generated. As with data-files it can use a limited form of * wildcards in file names.

extra-tmp-files: filename list

A list of additional files or directories to be removed by setup clean. These would typically be additional files created by additional hooks, such as the scheme described in the section on system-dependent parameters

Library
library

Build information for libraries. There can be only one library in a package, and it’s name is the same as package name set by global name field.

The library section should contain the following fields:

exposed-modules: identifier list
Required:if this package contains a library

A list of modules added by this package.

exposed: boolean
Default value:True

Some Haskell compilers (notably GHC) support the notion of packages being “exposed” or “hidden” which means the modules they provide can be easily imported without always having to specify which package they come from. However this only works effectively if the modules provided by all exposed packages do not overlap (otherwise a module import would be ambiguous).

Almost all new libraries use hierarchical module names that do not clash, so it is very uncommon to have to use this field. However it may be necessary to set exposed: False for some old libraries that use a flat module namespace or where it is known that the exposed modules would clash with other common modules.

reexported-modules: exportlist

Supported only in GHC 7.10 and later. A list of modules to reexport from this package. The syntax of this field is orig-pkg:Name as NewName to reexport module Name from orig-pkg with the new name NewName. We also support abbreviated versions of the syntax: if you omit as NewName, we’ll reexport without renaming; if you omit orig-pkg, then we will automatically figure out which package to reexport from, if it’s unambiguous.

Reexported modules are useful for compatibility shims when a package has been split into multiple packages, and they have the useful property that if a package provides a module, and another package reexports it under the same name, these are not considered a conflict (as would be the case with a stub module.) They can also be used to resolve name conflicts.

The library section may also contain build information fields (see the section on build information).

Cabal 2.0 and later support “internal libraries”, which are extra named libraries (as opposed to the usual unnamed library section). For example, suppose that your test suite needs access to some internal modules in your library, which you do not otherwise want to export. You could put these modules in an internal library, which the main library and the test suite build-depends upon. Then your Cabal file might look something like this:

name:           foo
version:        1.0
license:        BSD3
cabal-version:  >= 1.23
build-type:     Simple

library foo-internal
    exposed-modules: Foo.Internal
    build-depends: base

library
    exposed-modules: Foo.Public
    build-depends: foo-internal, base

test-suite test-foo
    type:       exitcode-stdio-1.0
    main-is:    test-foo.hs
    build-depends: foo-internal, base

Internal libraries are also useful for packages that define multiple executables, but do not define a publically accessible library. Internal libraries are only visible internally in the package (so they can only be added to the build-depends of same-package libraries, executables, test suites, etc.) Internal libraries locally shadow any packages which have the same name (so don’t name an internal library with the same name as an external dependency.)

Opening an interpreter session

While developing a package, it is often useful to make its code available inside an interpreter session. This can be done with the repl command:

$ cabal repl

The name comes from the acronym REPL, which stands for “read-eval-print-loop”. By default cabal repl loads the first component in a package. If the package contains several named components, the name can be given as an argument to repl. The name can be also optionally prefixed with the component’s type for disambiguation purposes. Example:

$ cabal repl foo
$ cabal repl exe:foo
$ cabal repl test:bar
$ cabal repl bench:baz
Freezing dependency versions

If a package is built in several different environments, such as a development environment, a staging environment and a production environment, it may be necessary or desirable to ensure that the same dependency versions are selected in each environment. This can be done with the freeze command:

$ cabal freeze

The command writes the selected version for all dependencies to the cabal.config file. All environments which share this file will use the dependency versions specified in it.

Generating dependency version bounds

Cabal also has the ability to suggest dependency version bounds that conform to Package Versioning Policy, which is a recommended versioning system for publicly released Cabal packages. This is done by running the gen-bounds command:

$ cabal gen-bounds

For example, given the following dependencies specified in build-depends:

build-depends:
  foo == 0.5.2
  bar == 1.1

gen-bounds will suggest changing them to the following:

build-depends:
  foo >= 0.5.2 && < 0.6
  bar >= 1.1 && < 1.2
Listing outdated dependency version bounds

Manually updating dependency version bounds in a .cabal file or a freeze file can be tedious, especially when there’s a lot of dependencies. The cabal outdated command is designed to help with that. It will print a list of packages for which there is a new version on Hackage that is outside the version bound specified in the build-depends field. The outdated command can also be configured to act on the freeze file (both old- and new-style) and ignore major (or all) version bumps on Hackage for a subset of dependencies.

The following flags are supported by the outdated command:

--freeze-file
Read dependency version bounds from the freeze file (cabal.config) instead of the package description file ($PACKAGENAME.cabal).
--new-freeze-file
Read dependency version bounds from the new-style freeze file (cabal.project.freeze) instead of the package description file.
--simple-output
Print only the names of outdated dependencies, one per line.
--exit-code
Exit with a non-zero exit code when there are outdated dependencies.
-q, --quiet
Don’t print any output. Implies -v0 and --exit-code.
--ignore PACKAGENAMES
Don’t warn about outdated dependency version bounds for the packages in this list.
--minor [PACKAGENAMES]
Ignore major version bumps for these packages. E.g. if there’s a version 2.0 of a package pkg on Hackage and the freeze file specifies the constraint pkg == 1.9, cabal outdated --freeze --minor=pkg will only consider the pkg outdated when there’s a version of pkg on Hackage satisfying pkg > 1.9 && < 2.0. --minor can also be used without arguments, in that case major version bumps are ignored for all packages.

Examples:

$ cd /some/package
$ cabal outdated
Outdated dependencies:
haskell-src-exts <1.17 (latest: 1.19.1)
language-javascript <0.6 (latest: 0.6.0.9)
unix ==2.7.2.0 (latest: 2.7.2.1)

$ cabal outdated --simple-output
haskell-src-exts
language-javascript
unix

$ cabal outdated --ignore=haskell-src-exts
Outdated dependencies:
language-javascript <0.6 (latest: 0.6.0.9)
unix ==2.7.2.0 (latest: 2.7.2.1)

$ cabal outdated --ignore=haskell-src-exts,language-javascript,unix
All dependencies are up to date.

$ cabal outdated --ignore=haskell-src-exts,language-javascript,unix -q
$ echo $?
0

$ cd /some/other/package
$ cabal outdated --freeze-file
Outdated dependencies:
HTTP ==4000.3.3 (latest: 4000.3.4)
HUnit ==1.3.1.1 (latest: 1.5.0.0)

$ cabal outdated --freeze-file --ignore=HTTP --minor=HUnit
Outdated dependencies:
HUnit ==1.3.1.1 (latest: 1.3.1.2)
Executables
executable name

Executable sections (if present) describe executable programs contained in the package and must have an argument after the section label, which defines the name of the executable. This is a freeform argument but may not contain spaces.

The executable may be described using the following fields, as well as build information fields (see the section on build information).

main-is: filename (required)

The name of the .hs or .lhs file containing the Main module. Note that it is the .hs filename that must be listed, even if that file is generated using a preprocessor. The source file must be relative to one of the directories listed in hs-source-dirs.

scope: token

Whether the executable is public (default) or private, i.e. meant to be run by other programs rather than the user. Private executables are installed into $libexecdir/$libexecsubdir.

Running executables

You can have Cabal build and run your executables by using the run command:

$ cabal run EXECUTABLE [-- EXECUTABLE_FLAGS]

This command will configure, build and run the executable EXECUTABLE. The double dash separator is required to distinguish executable flags from run’s own flags. If there is only one executable defined in the whole package, the executable’s name can be omitted. See the output of cabal help run for a list of options you can pass to cabal run.

Test suites
test name

Test suite sections (if present) describe package test suites and must have an argument after the section label, which defines the name of the test suite. This is a freeform argument, but may not contain spaces. It should be unique among the names of the package’s other test suites, the package’s executables, and the package itself. Using test suite sections requires at least Cabal version 1.9.2.

The test suite may be described using the following fields, as well as build information fields (see the section on build information).

type: interface (required)

The interface type and version of the test suite. Cabal supports two test suite interfaces, called exitcode-stdio-1.0 and detailed-0.9. Each of these types may require or disallow other fields as described below.

Test suites using the exitcode-stdio-1.0 interface are executables that indicate test failure with a non-zero exit code when run; they may provide human-readable log information through the standard output and error channels. The exitcode-stdio-1.0 type requires the main-is field.

main-is: filename
Required:exitcode-stdio-1.0
Disallowed:detailed-0.9

The name of the .hs or .lhs file containing the Main module. Note that it is the .hs filename that must be listed, even if that file is generated using a preprocessor. The source file must be relative to one of the directories listed in hs-source-dirs. This field is analogous to the main-is field of an executable section.

Test suites using the detailed-0.9 interface are modules exporting the symbol tests :: IO [Test]. The Test type is exported by the module Distribution.TestSuite provided by Cabal. For more details, see the example below.

The detailed-0.9 interface allows Cabal and other test agents to inspect a test suite’s results case by case, producing detailed human- and machine-readable log files. The detailed-0.9 interface requires the test-module field.

test-module: identifier
Required:detailed-0.9
Disallowed:exitcode-stdio-1.0

The module exporting the tests symbol.

Example: Package using exitcode-stdio-1.0 interface

The example package description and executable source file below demonstrate the use of the exitcode-stdio-1.0 interface.

foo.cabal
Name:           foo
Version:        1.0
License:        BSD3
Cabal-Version:  >= 1.9.2
Build-Type:     Simple

Test-Suite test-foo
    type:       exitcode-stdio-1.0
    main-is:    test-foo.hs
    build-depends: base
test-foo.hs
module Main where

import System.Exit (exitFailure)

main = do
    putStrLn "This test always fails!"
    exitFailure
Example: Package using detailed-0.9 interface

The example package description and test module source file below demonstrate the use of the detailed-0.9 interface. The test module also develops a simple implementation of the interface set by Distribution.TestSuite, but in actual usage the implementation would be provided by the library that provides the testing facility.

bar.cabal
Name:           bar
Version:        1.0
License:        BSD3
Cabal-Version:  >= 1.9.2
Build-Type:     Simple

Test-Suite test-bar
    type:       detailed-0.9
    test-module: Bar
    build-depends: base, Cabal >= 1.9.2
Bar.hs
module Bar ( tests ) where

import Distribution.TestSuite

tests :: IO [Test]
tests = return [ Test succeeds, Test fails ]
  where
    succeeds = TestInstance
        { run = return $ Finished Pass
        , name = "succeeds"
        , tags = []
        , options = []
        , setOption = \_ _ -> Right succeeds
        }
    fails = TestInstance
        { run = return $ Finished $ Fail "Always fails!"
        , name = "fails"
        , tags = []
        , options = []
        , setOption = \_ _ -> Right fails
        }
Running test suites

You can have Cabal run your test suites using its built-in test runner:

$ cabal configure --enable-tests
$ cabal build
$ cabal test

See the output of cabal help test for a list of options you can pass to cabal test.

Benchmarks
benchmark name
Since:Cabal 1.9.2

Benchmark sections (if present) describe benchmarks contained in the package and must have an argument after the section label, which defines the name of the benchmark. This is a freeform argument, but may not contain spaces. It should be unique among the names of the package’s other benchmarks, the package’s test suites, the package’s executables, and the package itself. Using benchmark sections requires at least Cabal version 1.9.2.

The benchmark may be described using the following fields, as well as build information fields (see the section on build information).

type: interface (required)

The interface type and version of the benchmark. At the moment Cabal only support one benchmark interface, called exitcode-stdio-1.0.

Benchmarks using the exitcode-stdio-1.0 interface are executables that indicate failure to run the benchmark with a non-zero exit code when run; they may provide human-readable information through the standard output and error channels.

main-is: filename
Required:exitcode-stdio-1.0

The name of the .hs or .lhs file containing the Main module. Note that it is the .hs filename that must be listed, even if that file is generated using a preprocessor. The source file must be relative to one of the directories listed in hs-source-dirs. This field is analogous to the main-is field of an executable section.

Example: Package using exitcode-stdio-1.0 interface

The example package description and executable source file below demonstrate the use of the exitcode-stdio-1.0 interface.

foo.cabal
Name:           foo
Version:        1.0
License:        BSD3
Cabal-Version:  >= 1.9.2
Build-Type:     Simple

Benchmark bench-foo
    type:       exitcode-stdio-1.0
    main-is:    bench-foo.hs
    build-depends: base, time
bench-foo.hs
{-# LANGUAGE BangPatterns #-}
module Main where

import Data.Time.Clock

fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

main = do
    start <- getCurrentTime
    let !r = fib 20
    end <- getCurrentTime
    putStrLn $ "fib 20 took " ++ show (diffUTCTime end start)
Running benchmarks

You can have Cabal run your benchmark using its built-in benchmark runner:

$ cabal configure --enable-benchmarks
$ cabal build
$ cabal bench

See the output of cabal help bench for a list of options you can pass to cabal bench.

Foreign libraries

Foreign libraries are system libraries intended to be linked against programs written in C or other “foreign” languages. They come in two primary flavours: dynamic libraries (.so files on Linux, .dylib files on OSX, .dll files on Windows, etc.) are linked against executables when the executable is run (or even lazily during execution), while static libraries (.a files on Linux/OSX, .lib files on Windows) get linked against the executable at compile time.

Foreign libraries only work with GHC 7.8 and later.

A typical stanza for a foreign library looks like

foreign-library myforeignlib
  type:                native-shared
  lib-version-info:    6:3:2

  if os(Windows)
    options: standalone
    mod-def-file: MyForeignLib.def

  other-modules:       MyForeignLib.SomeModule
                       MyForeignLib.SomeOtherModule
  build-depends:       base >=4.7 && <4.9
  hs-source-dirs:      src
  c-sources:           csrc/MyForeignLibWrapper.c
  default-language:    Haskell2010
type: foreign library type

Cabal recognizes native-static and native-shared here, although we currently only support building native-shared libraries.

options: foreign library option list

Options for building the foreign library, typically specific to the specified type of foreign library. Currently we only support standalone here. A standalone dynamic library is one that does not have any dependencies on other (Haskell) shared libraries; without the standalone option the generated library would have dependencies on the Haskell runtime library (libHSrts), the base library (libHSbase), etc. Currently, standalone must be used on Windows and must not be used on any other platform.

mod-def-file: filename

This option can only be used when creating dynamic Windows libraries (that is, when using native-shared and the os is Windows). If used, it must be a path to a _module definition file_. The details of module definition files are beyond the scope of this document; see the GHC manual for some details and some further pointers.

lib-version-info: current:revision:age

This field is currently only used on Linux.

This field specifies a Libtool-style version-info field that sets an appropriate ABI version for the foreign library. Note that the three numbers specified in this field do not directly specify the actual ABI version: 6:3:2 results in library version 4.2.3.

With this field set, the SONAME of the library is set, and symlinks are installed.

How you should bump this field on an ABI change depends on the breakage you introduce:

  • Programs using the previous version may use the new version as drop-in replacement, and programs using the new version can also work with the previous one. In other words, no recompiling nor relinking is needed. In this case, bump revision only, don’t touch current nor age.
  • Programs using the previous version may use the new version as drop-in replacement, but programs using the new version may use APIs not present in the previous one. In other words, a program linking against the new version may fail with “unresolved symbols” if linking against the old version at runtime: set revision to 0, bump current and age.
  • Programs may need to be changed, recompiled, and relinked in order to use the new version. Bump current, set revision and age to 0.

Also refer to the Libtool documentation on the version-info field.

lib-version-linux: version

This field is only used on Linux.

Specifies the library ABI version directly for foreign libraries built on Linux: so specifying 4.2.3 causes a library libfoo.so.4.2.3 to be built with SONAME libfoo.so.4, and appropriate symlinks libfoo.so.4 and libfoo.so to be installed.

Note that typically foreign libraries should export a way to initialize and shutdown the Haskell runtime. In the example above, this is done by the csrc/MyForeignLibWrapper.c file, which might look something like

#include <stdlib.h>
#include "HsFFI.h"

HsBool myForeignLibInit(void){
  int argc = 2;
  char *argv[] = { "+RTS", "-A32m", NULL };
  char **pargv = argv;

  // Initialize Haskell runtime
  hs_init(&argc, &pargv);

  // do any other initialization here and
  // return false if there was a problem
  return HS_BOOL_TRUE;
}

void myForeignLibExit(void){
  hs_exit();
}

With modern ghc regular libraries are installed in directories that contain package keys. This isn’t usually a problem because the package gets registered in ghc’s package DB and so we can figure out what the location of the library is. Foreign libraries however don’t get registered, which means that we’d have to have a way of finding out where a platform library got installed (other than by searching the lib/ directory). Instead, we install foreign libraries in ~/.cabal/lib, much like we install executables in ~/.cabal/bin.

Build information

The following fields may be optionally present in a library, executable, test suite or benchmark section, and give information for the building of the corresponding library or executable. See also the sections on system-dependent parameters and configurations for a way to supply system-dependent values for these fields.

build-depends: package list

A list of packages needed to build this one. Each package can be annotated with a version constraint.

Version constraints use the operators ==, >=, >, <, <= and a version number. Multiple constraints can be combined using && or ||. If no version constraint is specified, any version is assumed to be acceptable. For example:

library
  build-depends:
    base >= 2,
    foo >= 1.2.3 && < 1.3,
    bar

Dependencies like foo >= 1.2.3 && < 1.3 turn out to be very common because it is recommended practise for package versions to correspond to API versions (see PVP).

Since Cabal 1.6, there is a special wildcard syntax to help with such ranges

build-depends: foo ==1.2.*

It is only syntactic sugar. It is exactly equivalent to foo >= 1.2 && < 1.3.

Starting with Cabal 2.0, there’s a new syntactic sugar to support PVP-style major upper bounds conveniently, and is inspired by similiar syntactic sugar found in other language ecosystems where it’s often called the “Caret” operator:

build-depends: foo ^>= 1.2.3.4,
               bar ^>= 1

The declaration above is exactly equivalent to

build-depends: foo >= 1.2.3.4 && < 1.3,
               bar >= 1 && < 1.1

Note

Prior to Cabal 1.8, build-depends specified in each section were global to all sections. This was unintentional, but some packages were written to depend on it, so if you need your build-depends to be local to each section, you must specify at least Cabal-Version: >= 1.8 in your .cabal file.

Note

Cabal 1.20 experimentally supported module thinning and renaming in build-depends; however, this support has since been removed and should not be used.

other-modules: identifier list

A list of modules used by the component but not exposed to users. For a library component, these would be hidden modules of the library. For an executable, these would be auxiliary modules to be linked with the file named in the main-is field.

Note

Every module in the package must be listed in one of other-modules, library:exposed-modules or executable:main-is fields.

hs-source-dirs: directory list
Default value:.

Root directories for the module hierarchy.

For backwards compatibility, the old variant hs-source-dir is also recognized.

default-extensions: identifier list

A list of Haskell extensions used by every module. These determine corresponding compiler options enabled for all files. Extension names are the constructors of the Extension type. For example, CPP specifies that Haskell source files are to be preprocessed with a C preprocessor.

other-extensions: identifier list

A list of Haskell extensions used by some (but not necessarily all) modules. From GHC version 6.6 onward, these may be specified by placing a LANGUAGE pragma in the source files affected e.g.

{-# LANGUAGE CPP, MultiParamTypeClasses #-}

In Cabal-1.24 the dependency solver will use this and default-extensions information. Cabal prior to 1.24 will abort compilation if the current compiler doesn’t provide the extensions.

If you use some extensions conditionally, using CPP or conditional module lists, it is good to replicate the condition in other-extensions declarations:

other-extensions: CPP
if impl(ghc >= 7.5)
  other-extensions: PolyKinds

You could also omit the conditionally used extensions, as they are for information only, but it is recommended to replicate them in other-extensions declarations.

extensions: identifier list
Deprecated:

Deprecated in favor of default-extensions.

build-tool-depends: package:executable list

A list of Haskell programs needed to build this component. Each is specified by the package containing the executable and the name of the executable itself, separated by a colon, and optionally followed by a version bound. It is fine for the package to be the current one, in which case this is termed an internal, rather than external executable dependency.

External dependencies can (and should) contain a version bound like conventional build-depends dependencies. Internal deps should not contain a version bound, as they will be always resolved within the same configuration of the package in the build plan. Specifically, version bounds that include the package’s version will be warned for being extraneous, and version bounds that exclude the package’s version will raise and error for being impossible to follow.

Cabal can make sure that specified programs are built and on the PATH before building the component in question. It will always do so for internal dependencies, and also do so for external dependencies when using Nix-style local builds.

build-tool-depends was added in Cabal 2.0, and it will be ignored (with a warning) with old versions of Cabal. See build-tools for more information about backwards compatibility.

build-tools: program list
Deprecated:

Deprecated in favor of build-tool-depends, but see below for backwards compatibility information.

A list of Haskell programs needed to build this component. Each may be followed by an optional version bound. Confusingly, each program in the list either refer to one of three things:

  1. Another executables in the same package
  2. One of a hard-coded set of packages containing common build tools (possibly extended by a Custom setup script)
  3. A pre-built executable that should already be on the PATH (Supported only by Cabal 2.0 and later.)

These cases are listed in order of priority: an executable in the package will override any of the hard-coded packages with the same name, and a hard-coded package will override any executable on the PATH.

In the first two cases, the list entry is desugared into a build-tool-depends entry. In the first case, the entry is desugared into a build-tool-depends entry by prefixing with $pkg:. In the second case, it is desugared by looking up the package and executable name in a hard-coded table. In either case, the optional version bound is passed through unchanged. Refer to the documentation for build-tool-depends to understand the desugared field’s meaning, along with restrictions on version bounds.

Although this field is deprecated in favor of build-tool-depends, there are some situations where you may prefer to use build-tool in cases (1) and (2), as it is supported by more versions of Cabal. In case (3), build-tool-depends is better for backwards-compatibility, as it will be ignored by old versions of Cabal; if you add the executable to build-tools, a setup script built against old Cabal will choke. If an old version of Cabal is used, an end-user will have to manually arrange for the requested executable to be in your PATH.

buildable: boolean
Default value:True

Is the component buildable? Like some of the other fields below, this field is more useful with the slightly more elaborate form of the simple build infrastructure described in the section on system-dependent parameters.

ghc-options: token list

Additional options for GHC. You can often achieve the same effect using the extensions field, which is preferred.

Options required only by one module may be specified by placing an OPTIONS_GHC pragma in the source file affected.

As with many other fields, whitespace can be escaped by using Haskell string syntax. Example: ghc-options: -Wcompat "-with-rtsopts=-T -I1" -Wall.

ghc-prof-options: token list

Additional options for GHC when the package is built with profiling enabled.

Note that as of Cabal-1.24, the default profiling detail level defaults to exported-functions for libraries and toplevel-functions for executables. For GHC these correspond to the flags -fprof-auto-exported and -fprof-auto-top. Prior to Cabal-1.24 the level defaulted to none. These levels can be adjusted by the person building the package with the --profiling-detail and --library-profiling-detail flags.

It is typically better for the person building the package to pick the profiling detail level rather than for the package author. So unless you have special needs it is probably better not to specify any of the GHC -fprof-auto* flags here. However if you wish to override the profiling detail level, you can do so using the ghc-prof-options field: use -fno-prof-auto or one of the other -fprof-auto* flags.

ghc-shared-options: token list

Additional options for GHC when the package is built as shared library. The options specified via this field are combined with the ones specified via ghc-options, and are passed to GHC during both the compile and link phases.

includes: filename list

A list of header files to be included in any compilations via C. This field applies to both header files that are already installed on the system and to those coming with the package to be installed. The former files should be found in absolute paths, while the latter files should be found in paths relative to the top of the source tree or relative to one of the directories listed in include-dirs.

These files typically contain function prototypes for foreign imports used by the package. This is in contrast to install-includes, which lists header files that are intended to be exposed to other packages that transitively depend on this library.

install-includes: filename list

A list of header files from this package to be installed into $libdir/includes when the package is installed. Files listed in install-includes should be found in relative to the top of the source tree or relative to one of the directories listed in include-dirs.

install-includes is typically used to name header files that contain prototypes for foreign imports used in Haskell code in this package, for which the C implementations are also provided with the package. For example, here is a .cabal file for a hypothetical bindings-clib package that bundles the C source code for clib:

include-dirs:     cbits
c-sources:        clib.c
install-includes: clib.h

Now any package that depends (directly or transitively) on the bindings-clib library can use clib.h.

Note that in order for files listed in install-includes to be usable when compiling the package itself, they need to be listed in the includes field as well.

include-dirs: directory list

A list of directories to search for header files, when preprocessing with c2hs, hsc2hs, cpphs or the C preprocessor, and also when compiling via C. Directories can be absolute paths (e.g., for system directories) or paths that are relative to the top of the source tree. Cabal looks in these directories when attempting to locate files listed in includes and install-includes.

c-sources: filename list

A list of C source files to be compiled and linked with the Haskell files.

js-sources: filename list

A list of JavaScript source files to be linked with the Haskell files (only for JavaScript targets).

extra-libraries: token list

A list of extra libraries to link with.

extra-ghci-libraries: token list

A list of extra libraries to be used instead of ‘extra-libraries’ when the package is loaded with GHCi.

extra-lib-dirs: directory list

A list of directories to search for libraries.

cc-options: token list

Command-line arguments to be passed to the C compiler. Since the arguments are compiler-dependent, this field is more useful with the setup described in the section on system-dependent parameters.

cpp-options: token list

Command-line arguments for pre-processing Haskell code. Applies to haskell source and other pre-processed Haskell source like .hsc .chs. Does not apply to C code, that’s what cc-options is for.

ld-options: token list

Command-line arguments to be passed to the linker. Since the arguments are compiler-dependent, this field is more useful with the setup described in the section on system-dependent parameters.

pkgconfig-depends: package list

A list of pkg-config packages, needed to build this package. They can be annotated with versions, e.g. gtk+-2.0 >= 2.10, cairo >= 1.0. If no version constraint is specified, any version is assumed to be acceptable. Cabal uses pkg-config to find if the packages are available on the system and to find the extra compilation and linker options needed to use the packages.

If you need to bind to a C library that supports pkg-config (use pkg-config --list-all to find out if it is supported) then it is much preferable to use this field rather than hard code options into the other fields.

frameworks: token list

On Darwin/MacOS X, a list of frameworks to link to. See Apple’s developer documentation for more details on frameworks. This entry is ignored on all other platforms.

extra-frameworks-dirs: directory list

On Darwin/MacOS X, a list of directories to search for frameworks. This entry is ignored on all other platforms.

Configurations

Library and executable sections may include conditional blocks, which test for various system parameters and configuration flags. The flags mechanism is rather generic, but most of the time a flag represents certain feature, that can be switched on or off by the package user. Here is an example package description file using configurations:

Example: A package containing a library and executable programs
Name: Test1
Version: 0.0.1
Cabal-Version: >= 1.2
License: BSD3
Author:  Jane Doe
Synopsis: Test package to test configurations
Category: Example

Flag Debug
  Description: Enable debug support
  Default:     False

Flag WebFrontend
  Description: Include API for web frontend.
  -- Cabal checks if the configuration is possible, first
  -- with this flag set to True and if not it tries with False

Library
  Build-Depends:   base
  Exposed-Modules: Testing.Test1
  Extensions:      CPP

  if flag(debug)
    GHC-Options: -DDEBUG
    if !os(windows)
      CC-Options: "-DDEBUG"
    else
      CC-Options: "-DNDEBUG"

  if flag(webfrontend)
    Build-Depends: cgi > 0.42
    Other-Modules: Testing.WebStuff

Executable test1
  Main-is: T1.hs
  Other-Modules: Testing.Test1
  Build-Depends: base

  if flag(debug)
    CC-Options: "-DDEBUG"
    GHC-Options: -DDEBUG
Layout

Flags, conditionals, library and executable sections use layout to indicate structure. This is very similar to the Haskell layout rule. Entries in a section have to all be indented to the same level which must be more than the section header. Tabs are not allowed to be used for indentation.

As an alternative to using layout you can also use explicit braces {}. In this case the indentation of entries in a section does not matter, though different fields within a block must be on different lines. Here is a bit of the above example again, using braces:

Example: Using explicit braces rather than indentation for layout
Name: Test1
Version: 0.0.1
Cabal-Version: >= 1.2
License: BSD3
Author:  Jane Doe
Synopsis: Test package to test configurations
Category: Example

Flag Debug {
  Description: Enable debug support
  Default:     False
}

Library {
  Build-Depends:   base
  Exposed-Modules: Testing.Test1
  Extensions:      CPP
  if flag(debug) {
    GHC-Options: -DDEBUG
    if !os(windows) {
      CC-Options: "-DDEBUG"
    } else {
      CC-Options: "-DNDEBUG"
    }
  }
}
Configuration Flags
flag name

Flag section declares a flag which can be used in conditional blocks.

Flag names are case-insensitive and must match [[:alnum:]_][[:alnum:]_-]* regular expression.

Note

Hackage accepts ASCII-only flags, [a-zA-Z0-9_][a-zA-Z0-9_-]* regexp.

description: freeform

The description of this flag.

default: boolean
Default value:True

The default value of this flag.

Note

This value may be overridden in several ways. The rationale for having flags default to True is that users usually want new features as soon as they are available. Flags representing features that are not (yet) recommended for most users (such as experimental features or debugging support) should therefore explicitly override the default to False.

manual: boolean
Default value:False

By default, Cabal will first try to satisfy dependencies with the default flag value and then, if that is not possible, with the negated value. However, if the flag is manual, then the default value (which can be overridden by commandline flags) will be used.

Conditional Blocks

Conditional blocks may appear anywhere inside a library or executable section. They have to follow rather strict formatting rules. Conditional blocks must always be of the shape

if condition
   property-descriptions-or-conditionals

or

if condition
     property-descriptions-or-conditionals
else
     property-descriptions-or-conditionals

Note that the if and the condition have to be all on the same line.

Conditions

Conditions can be formed using boolean tests and the boolean operators || (disjunction / logical “or”), && (conjunction / logical “and”), or ! (negation / logical “not”). The unary ! takes highest precedence, || takes lowest. Precedence levels may be overridden through the use of parentheses. For example, os(darwin) && !arch(i386) || os(freebsd) is equivalent to (os(darwin) && !(arch(i386))) || os(freebsd).

The following tests are currently supported.

os(name)
Tests if the current operating system is name. The argument is tested against System.Info.os on the target system. There is unfortunately some disagreement between Haskell implementations about the standard values of System.Info.os. Cabal canonicalises it so that in particular os(windows) works on all implementations. If the canonicalised os names match, this test evaluates to true, otherwise false. The match is case-insensitive.
arch(name)
Tests if the current architecture is name. The argument is matched against System.Info.arch on the target system. If the arch names match, this test evaluates to true, otherwise false. The match is case-insensitive.
impl(compiler)

Tests for the configured Haskell implementation. An optional version constraint may be specified (for example impl(ghc >= 6.6.1)). If the configured implementation is of the right type and matches the version constraint, then this evaluates to true, otherwise false. The match is case-insensitive.

Note that including a version constraint in an impl test causes it to check for two properties:

  • The current compiler has the specified name, and
  • The compiler’s version satisfied the specified version constraint

As a result, !impl(ghc >= x.y.z) is not entirely equivalent to impl(ghc < x.y.z). The test !impl(ghc >= x.y.z) checks that:

  • The current compiler is not GHC, or
  • The version of GHC is earlier than version x.y.z.
flag(name)
Evaluates to the current assignment of the flag of the given name. Flag names are case insensitive. Testing for flags that have not been introduced with a flag section is an error.
true
Constant value true.
false
Constant value false.
Resolution of Conditions and Flags

If a package descriptions specifies configuration flags the package user can control these in several ways. If the user does not fix the value of a flag, Cabal will try to find a flag assignment in the following way.

  • For each flag specified, it will assign its default value, evaluate all conditions with this flag assignment, and check if all dependencies can be satisfied. If this check succeeded, the package will be configured with those flag assignments.
  • If dependencies were missing, the last flag (as by the order in which the flags were introduced in the package description) is tried with its alternative value and so on. This continues until either an assignment is found where all dependencies can be satisfied, or all possible flag assignments have been tried.

To put it another way, Cabal does a complete backtracking search to find a satisfiable package configuration. It is only the dependencies specified in the build-depends field in conditional blocks that determine if a particular flag assignment is satisfiable (build-tools are not considered). The order of the declaration and the default value of the flags determines the search order. Flags overridden on the command line fix the assignment of that flag, so no backtracking will be tried for that flag.

If no suitable flag assignment could be found, the configuration phase will fail and a list of missing dependencies will be printed. Note that this resolution process is exponential in the worst case (i.e., in the case where dependencies cannot be satisfied). There are some optimizations applied internally, but the overall complexity remains unchanged.

Meaning of field values when using conditionals

During the configuration phase, a flag assignment is chosen, all conditionals are evaluated, and the package description is combined into a flat package descriptions. If the same field both inside a conditional and outside then they are combined using the following rules.

  • Boolean fields are combined using conjunction (logical “and”).

  • List fields are combined by appending the inner items to the outer items, for example

    other-extensions: CPP
    if impl(ghc)
      other-extensions: MultiParamTypeClasses
    

    when compiled using GHC will be combined to

    other-extensions: CPP, MultiParamTypeClasses
    

    Similarly, if two conditional sections appear at the same nesting level, properties specified in the latter will come after properties specified in the former.

  • All other fields must not be specified in ambiguous ways. For example

    Main-is: Main.hs
    if flag(useothermain)
      Main-is: OtherMain.hs
    

    will lead to an error. Instead use

    if flag(useothermain)
      Main-is: OtherMain.hs
    else
      Main-is: Main.hs
    
Source Repositories
source-repository

It is often useful to be able to specify a source revision control repository for a package. Cabal lets you specifying this information in a relatively structured form which enables other tools to interpret and make effective use of the information. For example the information should be sufficient for an automatic tool to checkout the sources.

Cabal supports specifying different information for various common source control systems. Obviously not all automated tools will support all source control systems.

Cabal supports specifying repositories for different use cases. By declaring which case we mean automated tools can be more useful. There are currently two kinds defined:

  • The head kind refers to the latest development branch of the package. This may be used for example to track activity of a project or as an indication to outside developers what sources to get for making new contributions.
  • The this kind refers to the branch and tag of a repository that contains the sources for this version or release of a package. For most source control systems this involves specifying a tag, id or hash of some form and perhaps a branch. The purpose is to be able to reconstruct the sources corresponding to a particular package version. This might be used to indicate what sources to get if someone needs to fix a bug in an older branch that is no longer an active head branch.

You can specify one kind or the other or both. As an example here are the repositories for the Cabal library. Note that the this kind of repository specifies a tag.

source-repository head
  type:     darcs
  location: http://darcs.haskell.org/cabal/

source-repository this
  type:     darcs
  location: http://darcs.haskell.org/cabal-branches/cabal-1.6/
  tag:      1.6.1

The exact fields are as follows:

type: token

The name of the source control system used for this repository. The currently recognised types are:

  • darcs
  • git
  • svn
  • cvs
  • mercurial (or alias hg)
  • bazaar (or alias bzr)
  • arch
  • monotone

This field is required.

location: URL

The location of the repository. The exact form of this field depends on the repository type. For example:

  • for darcs: http://code.haskell.org/foo/
  • for git: git://github.com/foo/bar.git
  • for CVS: anoncvs@cvs.foo.org:/cvs

This field is required.

module: token

CVS requires a named module, as each CVS server can host multiple named repositories.

This field is required for the CVS repository type and should not be used otherwise.

branch: token

Many source control systems support the notion of a branch, as a distinct concept from having repositories in separate locations. For example CVS, SVN and git use branches while for darcs uses different locations for different branches. If you need to specify a branch to identify a your repository then specify it in this field.

This field is optional.

tag: token

A tag identifies a particular state of a source repository. The tag can be used with a this repository kind to identify the state of a repository corresponding to a particular package version or release. The exact form of the tag depends on the repository type.

This field is required for the this repository kind.

subdir: directory

Some projects put the sources for multiple packages under a single source repository. This field lets you specify the relative path from the root of the repository to the top directory for the package, i.e. the directory containing the package’s .cabal file.

This field is optional. It default to empty which corresponds to the root directory of the repository.

Downloading a package’s source

The cabal get command allows to access a package’s source code - either by unpacking a tarball downloaded from Hackage (the default) or by checking out a working copy from the package’s source repository.

$ cabal get [FLAGS] PACKAGES

The get command supports the following options:

-d --destdir PATH
Where to place the package source, defaults to (a subdirectory of) the current directory.
-s --source-repository [head|this|…]
Fork the package’s source repository using the appropriate version control system. The optional argument allows to choose a specific repository kind.
--index-state [HEAD|@<unix-timestamp>|<iso8601-utc-timestamp>]
Use source package index state as it existed at a previous time. Accepts unix-timestamps (e.g. @1474732068), ISO8601 UTC timestamps (e.g. 2016-09-24T17:47:48Z), or HEAD (default). This determines which package versions are available as well as which .cabal file revision is selected (unless --pristine is used).
--pristine
Unpack the original pristine tarball, rather than updating the .cabal file with the latest revision from the package archive.

Custom setup scripts

custom-setup
Since:Cabal 1.24

The optional custom-setup stanza contains information needed for the compilation of custom Setup.hs scripts,

custom-setup
  setup-depends:
    base >= 4.5 && < 4.11,
    Cabal < 1.25
setup-depends: package list
Since:Cabal 1.24

The dependencies needed to compile Setup.hs. See the build-depends field for a description of the syntax expected by this field.

Autogenerated modules

Modules that are built automatically at setup, created with a custom setup script, must appear on other-modules for the library, executable, test-suite or benchmark stanzas or also on library:exposed-modules for libraries to be used, but are not really on the package when distributed. This makes commands like sdist fail because the file is not found.

These special modules must appear again on the autogen-modules field of the stanza that is using it, besides other-modules or library:exposed-modules. With this there is no need to create complex build hooks for this poweruser case.

autogen-modules: module list

Right now executable:main-is modules are not supported on autogen-modules.

Library
    default-language: Haskell2010
    build-depends: base
    exposed-modules:
        MyLibrary
        MyLibHelperModule
    other-modules:
        MyLibModule
    autogen-modules:
        MyLibHelperModule

Executable Exe
    default-language: Haskell2010
    main-is: Dummy.hs
    build-depends: base
    other-modules:
        MyExeModule
        MyExeHelperModule
    autogen-modules:
        MyExeHelperModule

Accessing data files from package code

The placement on the target system of files listed in the data-files field varies between systems, and in some cases one can even move packages around after installation (see prefix independence). To enable packages to find these files in a portable way, Cabal generates a module called Paths_pkgname (with any hyphens in pkgname replaced by underscores) during building, so that it may be imported by modules of the package. This module defines a function

getDataFileName :: FilePath -> IO FilePath

If the argument is a filename listed in the data-files field, the result is the name of the corresponding file on the system on which the program is running.

Note

If you decide to import the Paths_pkgname module then it must be listed in the other-modules field just like any other module in your package and on autogen-modules as the file is autogenerated.

The Paths_pkgname module is not platform independent, as any other autogenerated module, so it does not get included in the source tarballs generated by sdist.

The Paths_pkgname module also includes some other useful functions and values, which record the version of the package and some other directories which the package has been configured to be installed into (e.g. data files live in getDataDir):

version :: Version

getBinDir :: IO FilePath
getLibDir :: IO FilePath
getDynLibDir :: IO FilePath
getDataDir :: IO FilePath
getLibexecDir :: IO FilePath
getSysconfDir :: IO FilePath

The actual location of all these directories can be individually overridden at runtime using environment variables of the form pkg_name_var, where pkg_name is the name of the package with all hyphens converted into underscores, and var is either bindir, libdir, dynlibdir, datadir, libexedir or sysconfdir. For example, the configured data directory for pretty-show is controlled with the pretty_show_datadir environment variable.

Accessing the package version

The aforementioned auto generated Paths_pkgname module also exports the constant version :: Version which is defined as the version of your package as specified in the version field.

System-dependent parameters

For some packages, especially those interfacing with C libraries, implementation details and the build procedure depend on the build environment. The build-type Configure can be used to handle many such situations. In this case, Setup.hs should be:

import Distribution.Simple
main = defaultMainWithHooks autoconfUserHooks

Most packages, however, would probably do better using the Simple build type and configurations.

The build-type Configure differs from Simple in two ways:

  • The package root directory must contain a shell script called configure. The configure step will run the script. This configure script may be produced by autoconf or may be hand-written. The configure script typically discovers information about the system and records it for later steps, e.g. by generating system-dependent header files for inclusion in C source files and preprocessed Haskell source files. (Clearly this won’t work for Windows without MSYS or Cygwin: other ideas are needed.)
  • If the package root directory contains a file called package.buildinfo after the configuration step, subsequent steps will read it to obtain additional settings for build information fields,to be merged with the ones given in the .cabal file. In particular, this file may be generated by the configure script mentioned above, allowing these settings to vary depending on the build environment.

The build information file should have the following structure:

buildinfo

executable: name buildinfo

executable: name buildinfo

where each buildinfo consists of settings of fields listed in the section on build information. The first one (if present) relates to the library, while each of the others relate to the named executable. (The names must match the package description, but you don’t have to have entries for all of them.)

Neither of these files is required. If they are absent, this setup script is equivalent to defaultMain.

Example: Using autoconf

This example is for people familiar with the autoconf tools.

In the X11 package, the file configure.ac contains:

AC_INIT([Haskell X11 package], [1.1], [libraries@haskell.org], [X11])

# Safety check: Ensure that we are in the correct source directory.
AC_CONFIG_SRCDIR([X11.cabal])

# Header file to place defines in
AC_CONFIG_HEADERS([include/HsX11Config.h])

# Check for X11 include paths and libraries
AC_PATH_XTRA
AC_TRY_CPP([#include <X11/Xlib.h>],,[no_x=yes])

# Build the package if we found X11 stuff
if test "$no_x" = yes
then BUILD_PACKAGE_BOOL=False
else BUILD_PACKAGE_BOOL=True
fi
AC_SUBST([BUILD_PACKAGE_BOOL])

AC_CONFIG_FILES([X11.buildinfo])
AC_OUTPUT

Then the setup script will run the configure script, which checks for the presence of the X11 libraries and substitutes for variables in the file X11.buildinfo.in:

buildable: @BUILD_PACKAGE_BOOL@
cc-options: @X_CFLAGS@
ld-options: @X_LIBS@

This generates a file X11.buildinfo supplying the parameters needed by later stages:

buildable: True
cc-options:  -I/usr/X11R6/include
ld-options:  -L/usr/X11R6/lib

The configure script also generates a header file include/HsX11Config.h containing C preprocessor defines recording the results of various tests. This file may be included by C source files and preprocessed Haskell source files in the package.

Note

Packages using these features will also need to list additional files such as configure, templates for .buildinfo files, files named only in .buildinfo files, header files and so on in the extra-source-files field to ensure that they are included in source distributions. They should also list files and directories generated by configure in the extra-tmp-files field to ensure that they are removed by setup clean.

Quite often the files generated by configure need to be listed somewhere in the package description (for example, in the install-includes field). However, we usually don’t want generated files to be included in the source tarball. The solution is again provided by the .buildinfo file. In the above example, the following line should be added to X11.buildinfo:

install-includes: HsX11Config.h

In this way, the generated HsX11Config.h file won’t be included in the source tarball in addition to HsX11Config.h.in, but it will be copied to the right location during the install process. Packages that use custom Setup.hs scripts can update the necessary fields programmatically instead of using the .buildinfo file.

Conditional compilation

Sometimes you want to write code that works with more than one version of a dependency. You can specify a range of versions for the dependency in the build-depends, but how do you then write the code that can use different versions of the API?

Haskell lets you preprocess your code using the C preprocessor (either the real C preprocessor, or cpphs). To enable this, add extensions: CPP to your package description. When using CPP, Cabal provides some pre-defined macros to let you test the version of dependent packages; for example, suppose your package works with either version 3 or version 4 of the base package, you could select the available version in your Haskell modules like this:

#if MIN_VERSION_base(4,0,0)
... code that works with base-4 ...
#else
... code that works with base-3 ...
#endif

In general, Cabal supplies a macro MIN_VERSION_``package``_(A,B,C) for each package depended on via build-depends. This macro is true if the actual version of the package in use is greater than or equal to A.B.C (using the conventional ordering on version numbers, which is lexicographic on the sequence, but numeric on each component, so for example 1.2.0 is greater than 1.0.3).

Since version 1.20, the MIN_TOOL_VERSION_``tool`` family of macros lets you condition on the version of build tools used to build the program (e.g. hsc2hs).

Since version 1.24, the macro CURRENT_COMPONENT_ID, which expands to the string of the component identifier that uniquely identifies this component. Furthermore, if the package is a library, the macro CURRENT_PACKAGE_KEY records the identifier that was passed to GHC for use in symbols and for type equality.

Since version 2.0, the macro CURRENT_PACKAGE_VERSION expands to the string version number of the current package.

Cabal places the definitions of these macros into an automatically-generated header file, which is included when preprocessing Haskell source code by passing options to the C preprocessor.

Cabal also allows to detect when the source code is being used for generating documentation. The __HADDOCK_VERSION__ macro is defined only when compiling via Haddock instead of a normal Haskell compiler. The value of the __HADDOCK_VERSION__ macro is defined as A*1000 + B*10 + C, where A.B.C is the Haddock version. This can be useful for working around bugs in Haddock or generating prettier documentation in some special cases.

More complex packages

For packages that don’t fit the simple schemes described above, you have a few options:

  • By using the build-type Custom, you can supply your own Setup.hs file, and customize the simple build infrastructure using hooks. These allow you to perform additional actions before and after each command is run, and also to specify additional preprocessors. A typical Setup.hs may look like this:

    import Distribution.Simple
    main = defaultMainWithHooks simpleUserHooks { postHaddock = posthaddock }
    
    posthaddock args flags desc info = ....
    

    See UserHooks in Distribution.Simple for the details, but note that this interface is experimental, and likely to change in future releases.

    If you use a custom Setup.hs file you should strongly consider adding a custom-setup stanza with a custom-setup:setup-depends field to ensure that your setup script does not break with future dependency versions.

  • You could delegate all the work to make, though this is unlikely to be very portable. Cabal supports this with the build-type Make and a trivial setup library Distribution.Make, which simply parses the command line arguments and invokes make. Here Setup.hs should look like this:

    import Distribution.Make
    main = defaultMain
    

    The root directory of the package should contain a configure script, and, after that has run, a Makefile with a default target that builds the package, plus targets install, register, unregister, clean, dist and docs. Some options to commands are passed through as follows:

    • The --with-hc-pkg, --prefix, --bindir, --libdir, --dynlibdir, --datadir, --libexecdir and --sysconfdir options to the configure command are passed on to the configure script. In addition the value of the --with-compiler option is passed in a --with-hc option and all options specified with --configure-option= are passed on.

    • The --destdir option to the copy command becomes a setting of a destdir variable on the invocation of make copy. The supplied Makefile should provide a copy target, which will probably look like this:

      copy :
              $(MAKE) install prefix=$(destdir)/$(prefix) \
                              bindir=$(destdir)/$(bindir) \
                              libdir=$(destdir)/$(libdir) \
                              dynlibdir=$(destdir)/$(dynlibdir) \
                              datadir=$(destdir)/$(datadir) \
                              libexecdir=$(destdir)/$(libexecdir) \
                              sysconfdir=$(destdir)/$(sysconfdir) \
      
  • Finally, with the build-type Custom, you can also write your own setup script from scratch. It must conform to the interface described in the section on building and installing packages, and you may use the Cabal library for all or part of the work. One option is to copy the source of Distribution.Simple, and alter it for your needs. Good luck.

Reporting Bugs and Stability of Cabal Interfaces

Reporting bugs and deficiencies

Please report any flaws or feature requests in the bug tracker.

For general discussion or queries email the libraries mailing list libraries@haskell.org. There is also a development mailing list cabal-devel@haskell.org.

Stability of Cabal interfaces

The Cabal library and related infrastructure is still under active development. New features are being added and limitations and bugs are being fixed. This requires internal changes and often user visible changes as well. We therefore cannot promise complete future-proof stability, at least not without halting all development work.

This section documents the aspects of the Cabal interface that we can promise to keep stable and which bits are subject to change.

Cabal file format

This is backwards compatible and mostly forwards compatible. New fields can be added without breaking older versions of Cabal. Fields can be deprecated without breaking older packages.

Command-line interface

Very Stable Command-line interfaces
  • ./setup configure
  • --prefix
  • --user
  • --ghc, --uhc
  • --verbose
  • --prefix
  • ./setup build
  • ./setup install
  • ./setup register
  • ./setup copy
Stable Command-line interfaces
Unstable command-line

Functions and Types

The Cabal library follows the Package Versioning Policy. This means that within a stable major release, for example 1.2.x, there will be no incompatible API changes. But minor versions increments, for example 1.2.3, indicate compatible API additions.

The Package Versioning Policy does not require any API guarantees between major releases, for example between 1.2.x and 1.4.x. In practise of course not everything changes between major releases. Some parts of the API are more prone to change than others. The rest of this section gives some informal advice on what level of API stability you can expect between major releases.

Very Stable API
  • defaultMain
  • defaultMainWithHooks defaultUserHooks

But regular defaultMainWithHooks isn’t stable since UserHooks changes.

Semi-stable API
  • UserHooks The hooks API will change in the future
  • Distribution.* is mostly declarative information about packages and is somewhat stable.
Unstable API

Everything under Distribution.Simple.* has no stability guarantee.

Hackage

The index format is a partly stable interface. It consists of a tar.gz file that contains directories with .cabal files in. In future it may contain more kinds of files so do not assume every file is a .cabal file. Incompatible revisions to the format would involve bumping the name of the index file, i.e., 00-index.tar.gz, 01-index.tar.gz etc.

Nix-style Local Builds

Nix-style local builds are a new build system implementation inspired by Nix. The Nix-style local build system is commonly called “new-build” for short after the cabal new-* family of commands that control it. However those names are only temporary until Nix-style local builds becomes the default.

Nix-style local builds combine the best of non-sandboxed and sandboxed Cabal:

  1. Like sandboxed Cabal today, we build sets of independent local packages deterministically and independent of any global state. new-build will never tell you that it can’t build your package because it would result in a “dangerous reinstall.” Given a particular state of the Hackage index, your build is completely reproducible. For example, you no longer need to compile packages with profiling ahead of time; just request profiling and new-build will rebuild all its dependencies with profiling automatically.
  2. Like non-sandboxed Cabal today, builds of external packages are cached in ~/.cabal/store, so that a package can be built once, and then reused anywhere else it is also used. No need to continually rebuild dependencies whenever you make a new sandbox: dependencies which can be shared, are shared.

Nix-style local builds were first released as beta in cabal-install 1.24. They currently work with all versions of GHC supported by that release: GHC 7.0 and later.

Some features described in this manual are not implemented. If you need them, please give us a shout and we’ll prioritize accordingly.

Quickstart

Suppose that you are in a directory containing a single Cabal package which you wish to build. You can configure and build it using Nix-style local builds with this command (configuring is not necessary):

$ cabal new-build

To open a GHCi shell with this package, use this command:

$ cabal new-repl

Developing multiple packages

Many Cabal projects involve multiple packages which need to be built together. To build multiple Cabal packages, you need to first create a cabal.project file which declares where all the local package directories live. For example, in the Cabal repository, there is a root directory with a folder per package, e.g., the folders Cabal and cabal-install. The cabal.project file specifies each folder as part of the project:

packages: Cabal/
          cabal-install/

The expectation is that a cabal.project is checked into your source control, to be used by all developers of a project. If you need to make local changes, they can be placed in cabal.project.local (which should not be checked in.)

Then, to build every component of every package, from the top-level directory, run the command: (Warning: cabal-install-1.24 does NOT have this behavior; you will need to upgrade to HEAD.)

$ cabal new-build

To build a specific package, you can either run new-build from the directory of the package in question:

$ cd cabal-install
$ cabal new-build

or you can pass the name of the package as an argument to cabal new-build (this works in any subdirectory of the project):

$ cabal new-build cabal-install

You can also specify a specific component of the package to build. For example, to build a test suite named package-tests, use the command:

$ cabal new-build package-tests

Targets can be qualified with package names. So to request package-tests from the Cabal package, use Cabal:package-tests.

Unlike sandboxes, there is no need to setup a sandbox or add-source projects; just check in cabal.project to your repository and new-build will just work.

Cookbook

How can I profile my library/application?

First, make sure you have HEAD; 1.24 is affected by #3790, which means that if any project which transitively depends on a package which has a Custom setup built against Cabal 1.22 or earlier will silently not work.

Create or edit your cabal.project.local, adding the following line:

profiling: True

Now, cabal new-build will automatically build all libraries and executables with profiling. You can fine-tune the profiling settings for each package using profiling-detail:

package p
    profiling-detail: toplevel-functions

Alternately, you can call cabal new-build --enable-profiling to temporarily build with profiling.

How it works

Local versus external packages

One of the primary innovations of Nix-style local builds is the distinction between local packages, which users edit and recompile and must be built per-project, versus external packages, which can be cached across projects. To be more precise:

  1. A local package is one that is listed explicitly in the packages, optional-packages or extra-packages field of a project. Usually, these refer to packages whose source code lives directly in a folder in your project (although, you can list an arbitrary Hackage package in extra-packages to force it to be treated as local).

Local packages, as well as the external packages (below) which depend on them, are built inplace, meaning that they are always built specifically for the project and are not installed globally. Inplace packages are not cached and not given unique hashes, which makes them suitable for packages which you want to edit and recompile.

  1. An external package is any package which is not listed in the packages field. The source code for external packages is usually retrieved from Hackage.

When an external package does not depend on an inplace package, it can be built and installed to a global store, which can be shared across projects. These build products are identified by a hash that over all of the inputs which would influence the compilation of a package (flags, dependency selection, etc.). Just as in Nix, these hashes uniquely identify the result of a build; if we compute this identifier and we find that we already have this ID built, we can just use the already built version.

The global package store is ~/.cabal/store (configurable via global store-dir option); if you need to clear your store for whatever reason (e.g., to reclaim disk space or because the global store is corrupted), deleting this directory is safe (new-build will just rebuild everything it needs on its next invocation).

This split motivates some of the UI choices for Nix-style local build commands. For example, flags passed to cabal new-build are only applied to local packages, so that adding a flag to cabal new-build doesn’t necessitate a rebuild of every transitive dependency in the global package store.

In cabal-install HEAD, Nix-style local builds also take advantage of a new Cabal library feature, per-component builds, where each component of a package is configured and built separately. This can massively speed up rebuilds of packages with lots of components (e.g., a package that defines multiple executables), as only one executable needs to be rebuilt. Packages that use Custom setup scripts are not currently built on a per-component basis.

Where are my build products?

A major deficiency in the current implementation of new-build is that there is no programmatic way to access the location of build products. The location of the build products is intended to be an internal implementation detail of new-build, but we also understand that many unimplemented features (e.g., new-test) can only be reasonably worked around by accessing build products directly.

The location where build products can be found varies depending on the version of cabal-install:

  • In cabal-install-1.24, the dist directory for a package p-0.1 is stored in dist-newstyle/build/p-0.1. For example, if you built an executable or test suite named pexe, it would be located at dist-newstyle/build/p-0.1/build/pexe/pexe.
  • In cabal-install HEAD, the dist directory for a package p-0.1 defining a library built with GHC 8.0.1 on 64-bit Linux is dist-newstyle/build/x86_64-linux/ghc-8.0.1/p-0.1. When per-component builds are enabled (any non-Custom package), a subcomponent like an executable or test suite named pexe will be stored at dist-newstyle/build/x86_64-linux/ghc-8.0.1/p-0.1/c/pexe; thus, the full path of the executable is dist-newstyle/build/x86_64-linux/ghc-8.0.1/p-0.1/c/pexe/build/pexe/pexe (you can see why we want this to be an implementation detail!)

The paths are a bit longer in HEAD but the benefit is that you can transparently have multiple builds with different versions of GHC. We plan to add the ability to create aliases for certain build configurations, and more convenient paths to access particularly useful build products like executables.

Caching

Nix-style local builds sport a robust caching system which help reduce the time it takes to execute a rebuild cycle. While the details of how cabal-install does caching are an implementation detail and may change in the future, knowing what gets cached is helpful for understanding the performance characteristics of invocations to new-build. The cached intermediate results are stored in dist-newstyle/cache; this folder can be safely deleted to clear the cache.

The following intermediate results are cached in the following files in this folder (the most important two are first):

solver-plan (binary)
The result of calling the dependency solver, assuming that the Hackage index, local cabal.project file, and local cabal files are unmodified. (Notably, we do NOT have to dependency solve again if new build products are stored in the global store; the invocation of the dependency solver is independent of what is already available in the store.)
source-hashes (binary)
The hashes of all local source files. When all local source files of a local package are unchanged, cabal new-build will skip invoking setup build entirely (saving us from a possibly expensive call to ghc --make). The full list of source files participating in compilation are determined using setup sdist --list-sources (thus, if you do not list all your source files in a Cabal file, you may fail to recompile when you edit them.)
config (same format as cabal.project)
The full project configuration, merged from cabal.project (and friends) as well as the command line arguments.
compiler (binary)
The configuration of the compiler being used to build the project.
improved-plan (binary)
Like solver-plan, but with all non-inplace packages improved into pre-existing copies from the store.

Note that every package also has a local cache managed by the Cabal build system, e.g., in $distdir/cache.

There is another useful file in dist-newstyle/cache, plan.json, which is a JSON serialization of the computed install plan. (TODO: docs)

Commands

We now give an in-depth description of all the commands, describing the arguments and flags they accept.

cabal new-configure

cabal new-configure takes a set of arguments and writes a cabal.project.local file based on the flags passed to this command. cabal new-configure FLAGS; cabal new-build is roughly equivalent to cabal new-build FLAGS, except that with new-configure the flags are persisted to all subsequent calls to new-build.

cabal new-configure is intended to be a convenient way to write out a cabal.project.local for simple configurations; e.g., cabal new-configure -w ghc-7.8 would ensure that all subsequent builds with cabal new-build are performed with the compiler ghc-7.8. For more complex configuration, we recommend writing the cabal.project.local file directly (or placing it in cabal.project!)

cabal new-configure inherits options from Cabal. semantics:

  • Any flag accepted by ./Setup configure.
  • Any flag accepted by cabal configure beyond ./Setup configure, namely --cabal-lib-version, --constraint, --preference and --solver.
  • Any flag accepted by cabal install beyond ./Setup configure.
  • Any flag accepted by ./Setup haddock.

The options of all of these flags apply only to local packages in a project; this behavior is different than that of cabal install, which applies flags to every package that would be built. The motivation for this is to avoid an innocuous addition to the flags of a package resulting in a rebuild of every package in the store (which might need to happen if a flag actually applied to every transitive dependency). To apply options to an external package, use a package stanza in a cabal.project file.

cabal new-build

cabal new-build takes a set of targets and builds them. It automatically handles building and installing any dependencies of these targets.

A target can take any of the following forms:

  • A package target: package, which specifies that all enabled components of a package to be built. By default, test suites and benchmarks are not enabled, unless they are explicitly requested (e.g., via --enable-tests.)

  • A component target: [package:][ctype:]component, which specifies a specific component (e.g., a library, executable, test suite or benchmark) to be built.

  • All packages: all, which specifies all packages within the project.

  • Components of a particular type: package:ctypes, all:ctypes: which specifies all components of the given type. Where valid ctypes are:

    • libs, libraries,
    • flibs, foreign-libraries,
    • exes, executables,
    • tests,
    • benches, benchmarks.

In component targets, package: and ctype: (valid component types are lib, flib, exe, test and bench) can be used to disambiguate when multiple packages define the same component, or the same component name is used in a package (e.g., a package foo defines both an executable and library named foo). We always prefer interpreting a target as a package name rather than as a component name.

Some example targets:

$ cabal new-build lib:foo-pkg       # build the library named foo-pkg
$ cabal new-build foo-pkg:foo-tests # build foo-tests in foo-pkg

(There is also syntax for specifying module and file targets, but it doesn’t currently do anything.)

Beyond a list of targets, cabal new-build accepts all the flags that cabal new-configure takes. Most of these flags are only taken into consideration when building local packages; however, some flags may cause extra store packages to be built (for example, --enable-profiling will automatically make sure profiling libraries for all transitive dependencies are built and installed.)

cabal new-repl

cabal new-repl TARGET loads all of the modules of the target into GHCi as interpreted bytecode. It takes the same flags as cabal new-build.

Currently, it is not supported to pass multiple targets to new-repl (new-repl will just successively open a separate GHCi session for each target.)

cabal new-freeze

cabal new-freeze writes out a cabal.project.freeze file which records all of the versions and flags which that are picked by the solver under the current index and flags. A cabal.project.freeze file has the same syntax as cabal.project and looks something like this:

constraints: HTTP ==4000.3.3,
             HTTP +warp-tests -warn-as-error -network23 +network-uri -mtl1 -conduit10,
             QuickCheck ==2.9.1,
             QuickCheck +templatehaskell,
             -- etc...

For end-user executables, it is recommended that you distribute the cabal.project.freeze file in your source repository so that all users see a consistent set of dependencies. For libraries, this is not recommended: users often need to build against different versions of libraries than what you developed against.

Unsupported commands

The following commands are not currently supported:

cabal new-test (#3638)
Workaround: run the test executable directly (see Where are my build products?)
cabal new-bench (#3638)
Workaround: run the benchmark executable directly (see Where are my build products?)
cabal new-run (#3638)
Workaround: run the executable directly (see Where are my build products?)
cabal new-exec
Workaround: if you wanted to execute GHCi, consider using cabal new-repl instead. Otherwise, use -v to find the list of flags GHC is being invoked with and pass it manually.
cabal new-haddock (#3535)
Workaround: run cabal act-as-setup -- haddock --builddir=dist-newstyle/build/pkg-0.1 (or execute the Custom setup script directly).
cabal new-install (#3737)
Workaround: no good workaround at the moment. (But note that you no longer need to install libraries before building!)

Configuring builds with cabal.project

cabal.project files support a variety of options which configure the details of your build. The general syntax of a cabal.project file is similar to that of a Cabal file: there are a number of fields, some of which live inside stanzas:

packages: */*.cabal
with-compiler: /opt/ghc/8.0.1/bin/ghc

package cryptohash
  optimization: False

In general, the accepted field names coincide with the accepted command line flags that cabal install and other commands take. For example, cabal new-configure --enable-profiling will write out a project file with profiling: True.

The full configuration of a project is determined by combining the following sources (later entries override earlier ones):

  1. ~/.cabal/config (the user-wide global configuration)
  2. cabal.project (the project configuratoin)
  3. cabal.project.freeze (the output of cabal new-freeze)
  4. cabal.project.local (the output of cabal new-configure)

Specifying the local packages

The following top-level options specify what the local packages of a project are:

packages: package location list (space or comma separated)
Default value:./*.cabal

Specifies the list of package locations which contain the local packages to be built by this project. Package locations can take the following forms:

  1. They can specify a Cabal file, or a directory containing a Cabal file, e.g., packages: Cabal cabal-install/cabal-install.cabal.
  2. They can specify a glob-style wildcards, which must match one or more (a) directories containing a (single) Cabal file, (b) Cabal files (extension .cabal), or (c) [STRIKEOUT:tarballs which contain Cabal packages (extension .tar.gz)] (not implemented yet). For example, to match all Cabal files in all subdirectories, as well as the Cabal projects in the parent directories foo and bar, use packages: */*.cabal ../{foo,bar}/
  3. [STRIKEOUT:They can specify an http, https or file URL, representing the path to a remote tarball to be downloaded and built.] (not implemented yet)

There is no command line variant of this field; see #3585.

optional-packages: package location list (space or comma-separated)
Default value:./*/*.cabal

Like packages, specifies a list of package locations containing local packages to be built. Unlike packages, if we glob for a package, it is permissible for the glob to match against zero packages. The intended use-case for optional-packages is to make it so that vendored packages can be automatically picked up if they are placed in a subdirectory, but not error if there aren’t any.

There is no command line variant of this field.

extra-packages: package list with version bounds (comma separated)

[STRIKEOUT:Specifies a list of external packages from Hackage which should be considered local packages.] (Not implemented)

There is no command line variant of this field.

[STRIKEOUT:There is also a stanza source-repository-package for specifying packages from an external version control.] (Not implemented.)

All local packages are vendored, in the sense that if other packages (including external ones from Hackage) depend on a package with the name of a local package, the local package is preferentially used. This motivates the default settings:

packages: ./*.cabal
optional-packages: ./*/*.cabal

…any package can be vendored simply by making a checkout in the top-level project directory, as might be seen in this hypothetical directory layout:

foo.cabal
foo-helper/     # local package
unix/           # vendored external package

All of these options support globs. cabal new-build has its own glob format:

  • Anywhere in a path, as many times as you like, you can specify an asterisk * wildcard. E.g., */*.cabal matches all .cabal files in all immediate subdirectories. Like in glob(7), asterisks do not match hidden files unless there is an explicit period, e.g., .*/foo.cabal will match .private/foo.cabal (but */foo.cabal will not).
  • You can use braces to specify specific directories; e.g., {vendor,pkgs}/*.cabal matches all Cabal files in the vendor and pkgs subdirectories.

Formally, the format described by the following BNF:

FilePathGlob    ::= FilePathRoot FilePathGlobRel
FilePathRoot    ::= {- empty -}        # relative to cabal.project
                  | "/"                # Unix root
                  | [a-zA-Z] ":" [/\\] # Windows root
                  | "~"                # home directory
FilePathGlobRel ::= Glob "/"  FilePathGlobRel # Unix directory
                  | Glob "\\" FilePathGlobRel # Windows directory
                  | Glob         # file
                  | {- empty -}  # trailing slash
Glob      ::= GlobPiece *
GlobPiece ::= "*"            # wildcard
            | [^*{},/\\] *   # literal string
            | "\\" [*{},]    # escaped reserved character
            | "{" Glob "," ... "," Glob "}" # union (match any of these)

Global configuration options

The following top-level configuration options are not specific to any package, and thus apply globally:

verbose: nat
--verbose=n, -vn
Default value:1

Control the verbosity of cabal commands, valid values are from 0 to 3.

The command line variant of this field is --verbose=2; a short form -v2 is also supported.

jobs: nat or $ncpus
--jobs=n, -jn , --jobs=$ncpus
Default value:1

Run nat jobs simultaneously when building. If $ncpus is specified, run the number of jobs equal to the number of CPUs. Package building is often quite parallel, so turning on parallelism can speed up build times quite a bit!

The command line variant of this field is --jobs=2; a short form -j2 is also supported; a bare --jobs or -j is equivalent to --jobs=$ncpus.

keep-going: boolean
--keep-going
Default value:False

If true, after a build failure, continue to build other unaffected packages.

The command line variant of this field is --keep-going.

--builddir=DIR

Specifies the name of the directory where build products for build will be stored; defaults to dist-newstyle. If a relative name is specified, this directory is resolved relative to the root of the project (i.e., where the cabal.project file lives.)

This option cannot be specified via a cabal.project file.

--project-file=FILE

Specifies the name of the project file used to specify the rest of the top-level configuration; defaults to cabal.project. This name not only specifies the name of the main project file, but also the auxiliary project files cabal.project.freeze and cabal.project.local; for example, if you specify --project-file=my.project, then the other files that will be probed are my.project.freeze and my.project.local.

If the specified project file is a relative path, we will look for the file relative to the current working directory, and then for the parent directory, until the project file is found or we have hit the top of the user’s home directory.

This option cannot be specified via a cabal.project file.

--store-dir=DIR

Specifies the name of the directory of the global package store.

Solver configuration options

The following settings control the behavior of the dependency solver:

constraints: constraints list (comma separated)
--constraint="pkg > 2.0"

Add extra constraints to the version bounds, flag settings, and other properties a solver can pick for a package. For example:

constraints: bar == 2.1

A package can be specified multiple times in constraints, in which case the specified constraints are intersected. This is useful, since the syntax does not allow you to specify multiple constraints at once. For example, to specify both version bounds and flag assignments, you would write:

constraints: bar == 2.1,
             bar +foo -baz

Valid constraints take the same form as for the constraint command line option.

preferences: preference (comma separated)
--preference="pkg > 2.0"

Like constraints, but the solver will attempt to satisfy these preferences on a best-effort basis. The resulting install is locally optimal with respect to preferences; specifically, no single package could be replaced with a more preferred version that still satisfies the hard constraints.

Operationally, preferences can cause the solver to attempt certain version choices of a package before others, which can improve dependency solver runtime.

One way to use preferences is to take a known working set of constraints (e.g., via cabal new-freeze) and record them as preferences. In this case, the solver will first attempt to use this configuration, and if this violates hard constraints, it will try to find the minimal number of upgrades to satisfy the hard constraints again.

The command line variant of this field is --preference="pkg >= 2.0"; to specify multiple preferences, pass the flag multiple times.

allow-newer: none, all or list of scoped package names (space or comma separated)
--allow-newer , --allow-newer=[none, all , pkg]
Default value:none

Allow the solver to pick an newer version of some packages than would normally be permitted by than the build-depends bounds of packages in the install plan. This option may be useful if the dependency solver cannot otherwise find a valid install plan.

For example, to relax pkgs build-depends upper bound on dep-pkg, write a scoped package name of the form:

allow-newer: pkg:dep-pkg

This syntax is recommended, as it is often only a single package whose upper bound is misbehaving. In this case, the upper bounds of other packages should still be respected; indeed, relaxing the bound can break some packages which test the selected version of packages.

However, in some situations (e.g., when attempting to build packages on a new version of GHC), it is useful to disregard all upper-bounds, with respect to a package or all packages. This can be done by specifying just a package name, or using the keyword all to specify all packages:

-- Disregard upper bounds involving the dependencies on
-- packages bar, baz and quux
allow-newer: bar, baz, quux

-- Disregard all upper bounds when dependency solving
allow-newer: all

allow-newer is often used in conjunction with a constraint (in the cfg-field:constraints field) forcing the usage of a specific, newer version of a package.

The command line variant of this field is --allow-newer=bar. A bare --allow-newer is equivalent to --allow-newer=all.

allow-older: none, all, list of scoped package names (space or comma separated)
--allow-older , --allow-older=[none, all , pkg]
Default value:none

Like allow-newer, but applied to lower bounds rather than upper bounds.

The command line variant of this field is --allow-older=all. A bare --allow-older is equivalent to --allow-older=all.

index-state: HEAD, unix-timestamp, ISO8601 UTC timestamp.
Since:Cabal 2.0
Default value:HEAD

This allows to change the source package index state the solver uses to compute install-plans. This is particularly useful in combination with freeze-files in order to also freeze the state the package index was in at the time the install-plan was frozen.

-- UNIX timestamp format example
index-state: @1474739268

-- ISO8601 UTC timestamp format example
-- This format is used by 'cabal new-configure'
-- for storing `--index-state` values.
index-state: 2016-09-24T17:47:48Z

Package configuration options

Package options affect the building of specific packages. There are two ways a package option can be specified:

  • They can be specified at the top-level, in which case they apply only to local package, or
  • They can be specified inside a package stanza, in which case they apply to the build of the package, whether or not it is local or external.

For example, the following options specify that optimization should be turned off for all local packages, and that bytestring (possibly an external dependency) should be built with -fno-state-hack:

optimization: False

package bytestring
    ghc-options: -fno-state-hack

ghc-options is not specifically described in this documentation, but is one of many fields for configuring programs. They take the form progname-options and progname-location, and can only be set inside package stanzas. (TODO: They are not supported at top-level, see #3579.)

At the moment, there is no way to specify an option to apply to all external packages or all inplace packages. Additionally, it is only possible to specify these options on the command line for all local packages (there is no per-package command line interface.)

Some flags were added by more recent versions of the Cabal library. This means that they are NOT supported by packages which use Custom setup scripts that require a version of the Cabal library older than when the feature was added.

flags: list of +flagname or -flagname (space separated)
--flags="+foo -bar", -ffoo , -f-bar

Force all flags specified as +flagname to be true, and all flags specified as -flagname to be false. For example, to enable the flag foo and disable bar, set:

flags: +foo -bar

If there is no leading punctuation, it is assumed that the flag should be enabled; e.g., this is equivalent:

flags: foo -bar

Flags are per-package, so it doesn’t make much sense to specify flags at the top-level, unless you happen to know that all of your local packages support the same named flags. If a flag is not supported by a package, it is ignored.

See also the solver configuration field constraints.

The command line variant of this flag is --flags. There is also a shortened form -ffoo -f-bar.

A common mistake is to say cabal new-build -fhans, where hans is a flag for a transitive dependency that is not in the local package; in this case, the flag will be silently ignored. If haskell-tor is the package you want this flag to apply to, try --constraint="haskell-tor +hans" instead.

with-compiler: executable
--with-compiler=executable

Specify the path to a particular compiler to be used. If not an absolute path, it will be resolved according to the PATH environment. The type of the compiler (GHC, GHCJS, etc) must be consistent with the setting of the compiler field.

The most common use of this option is to specify a different version of your compiler to be used; e.g., if you have ghc-7.8 in your path, you can specify with-compiler: ghc-7.8 to use it.

This flag also sets the default value of with-hc-pkg, using the heuristic that it is named ghc-pkg-7.8 (if your executable name is suffixed with a version number), or is the executable named ghc-pkg in the same directory as the ghc directory. If this heuristic does not work, set with-hc-pkg explicitly.

For inplace packages, cabal new-build maintains a separate build directory for each version of GHC, so you can maintain multiple build trees for different versions of GHC without clobbering each other.

At the moment, it’s not possible to set with-compiler on a per-package basis, but eventually we plan on relaxing this restriction. If this is something you need, give us a shout.

The command line variant of this flag is --with-compiler=ghc-7.8; there is also a short version -w ghc-7.8.

with-hc-pkg: executable
--with-hc-pkg=executable

Specify the path to the package tool, e.g., ghc-pkg. This package tool must be compatible with the compiler specified by with-compiler (generally speaking, it should be precisely the tool that was distributed with the compiler). If this option is omitted, the default value is determined from with-compiler.

The command line variant of this flag is --with-hc-pkg=ghc-pkg-7.8.

optimization: nat
--enable-optimization
--disable-optimization
Default value:1

Build with optimization. This is appropriate for production use, taking more time to build faster libraries and programs.

The optional nat value is the optimisation level. Some compilers support multiple optimisation levels. The range is 0 to 2. Level 0 disables optimization, level 1 is the default. Level 2 is higher optimisation if the compiler supports it. Level 2 is likely to lead to longer compile times and bigger generated code. If you are not planning to run code, turning off optimization will lead to better build times and less code to be rebuilt when a module changes.

We also accept True (equivalent to 1) and False (equivalent to 0).

Note that as of GHC 8.0, GHC does not recompile when optimization levels change (see GHC #10923), so if you change the optimization level for a local package you may need to blow away your old build products in order to rebuild with the new optimization level.

The command line variant of this flag is -O2 (with -O1 equivalent to -O). There are also long-form variants --enable-optimization and --disable-optimization.

configure-options: args (space separated)
--configure-option=arg

A list of extra arguments to pass to the external ./configure script, if one is used. This is only useful for packages which have the Configure build type. See also the section on system-dependent parameters.

The command line variant of this flag is --configure-option=arg, which can be specified multiple times to pass multiple options.

compiler: ghc, ghcjs, jhc, lhc, uhc or haskell-suite
--compiler=compiler
Default value:ghc

Specify which compiler toolchain to be used. This is independent of with-compiler, because the choice of toolchain affects Cabal’s build logic.

The command line variant of this flag is --compiler=ghc.

tests: boolean
--enable-tests
--disable-tests
Default value:False

Force test suites to be enabled. For most users this should not be needed, as we always attempt to solve for test suite dependencies, even when this value is False; furthermore, test suites are automatically enabled if they are requested as a built target.

The command line variant of this flag is --enable-tests and --disable-tests.

benchmarks: boolean
--enable-benchmarks
--disable-benchmarks
Default value:False

Force benchmarks to be enabled. For most users this should not be needed, as we always attempt to solve for benchmark dependencies, even when this value is False; furthermore, benchmarks are automatically enabled if they are requested as a built target.

The command line variant of this flag is --enable-benchmarks and --disable-benchmarks.

extra-prog-path: paths (newline or comma separated)
--extra-prog-path=PATH
Since:Cabal 1.18

A list of directories to search for extra required programs. Most users should not need this, as programs like happy and alex will automatically be installed and added to the path. This can be useful if a Custom setup script relies on an exotic extra program.

The command line variant of this flag is --extra-prog-path=PATH, which can be specified multiple times.

run-tests: boolean
--run-tests
Default value:False

Run the package test suite upon installation. This is useful for saying “When this package is installed, check that the test suite passes, terminating the rest of the build if it is broken.”

Warning

One deficiency: the run-tests setting of a package is NOT recorded as part of the hash, so if you install something without run-tests and then turn on run-tests, we won’t subsequently test the package. If this is causing you problems, give us a shout.

The command line variant of this flag is --run-tests.

Object code options
debug-info: boolean
--enable-debug-info
--disable-debug-info
Since:Cabal 1.22
Default value:False

If the compiler (e.g., GHC 7.10 and later) supports outputing OS native debug info (e.g., DWARF), setting debug-info: True will instruct it to do so. See the GHC wiki page on DWARF for more information about this feature.

(This field also accepts numeric syntax, but as of GHC 8.0 this doesn’t do anything.)

The command line variant of this flag is --enable-debug-info and --disable-debug-info.

split-objs: boolean
--enable-split-objs
--disable-split-objs
Default value:False

Use the GHC -split-objs feature when building the library. This reduces the final size of the executables that use the library by allowing them to link with only the bits that they use rather than the entire library. The downside is that building the library takes longer and uses considerably more memory.

The command line variant of this flag is --enable-split-objs and --disable-split-objs.

executable-stripping: boolean
--enable-executable-stripping
--disable-executable-stripping
Default value:True

When installing binary executable programs, run the strip program on the binary. This can considerably reduce the size of the executable binary file. It does this by removing debugging information and symbols.

Not all Haskell implementations generate native binaries. For such implementations this option has no effect.

(TODO: Check what happens if you combine this with debug-info.)

The command line variant of this flag is --enable-executable-stripping and --disable-executable-stripping.

library-stripping: boolean
--enable-library-stripping
--disable-library-stripping
Since:Cabal 1.19

When installing binary libraries, run the strip program on the binary, saving space on the file system. See also executable-stripping.

The command line variant of this flag is --enable-library-stripping and --disable-library-stripping.

Executable options
program-prefix: prefix
--program-prefix=prefix

[STRIKEOUT:Prepend prefix to installed program names.] (Currently implemented in a silly and not useful way. If you need this to work give us a shout.)

prefix may contain the following path variables: $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

The command line variant of this flag is --program-prefix=foo-.

program-suffix: suffix
--program-suffix=suffix

[STRIKEOUT:Append suffix to installed program names.] (Currently implemented in a silly and not useful way. If you need this to work give us a shout.)

The most obvious use for this is to append the program’s version number to make it possible to install several versions of a program at once: program-suffix: $version.

suffix may contain the following path variables: $pkgid, $pkg, $version, $compiler, $os, $arch, $abi, $abitag

The command line variant of this flag is --program-suffix='$version'.

Dynamic linking options
shared: boolean
--enable-shared
--disable-shared
Default value:False

Build shared library. This implies a separate compiler run to generate position independent code as required on most platforms.

The command line variant of this flag is --enable-shared and --disable-shared.

executable-dynamic: boolean
--enable-executable-dynamic
--disable-executable-dynamic
Default value:False

Link executables dynamically. The executable’s library dependencies should be built as shared objects. This implies shared: True unless shared: False is explicitly specified.

The command line variant of this flag is --enable-executable-dynamic and --disable-executable-dynamic.

library-for-ghci: boolean
--enable-library-for-ghci
--disable-library-for-ghci
Default value:True

Build libraries suitable for use with GHCi. This involves an extra linking step after the build.

Not all platforms support GHCi and indeed on some platforms, trying to build GHCi libs fails. In such cases, consider setting library-for-ghci: False.

The command line variant of this flag is --enable-library-for-ghci and --disable-library-for-ghci.

relocatable:
--relocatable
Since:Cabal 1.21
Default value:False

[STRIKEOUT:Build a package which is relocatable.] (TODO: It is not clear what this actually does, or if it works at all.)

The command line variant of this flag is --relocatable.

Foreign function interface options
extra-include-dirs: directories (comma or newline separated list)
--extra-include-dirs=DIR

An extra directory to search for C header files. You can use this flag multiple times to get a list of directories.

You might need to use this flag if you have standard system header files in a non-standard location that is not mentioned in the package’s .cabal file. Using this option has the same affect as appending the directory dir to the include-dirs field in each library and executable in the package’s .cabal file. The advantage of course is that you do not have to modify the package at all. These extra directories will be used while building the package and for libraries it is also saved in the package registration information and used when compiling modules that use the library.

The command line variant of this flag is --extra-include-dirs=DIR, which can be specified multiple times.

extra-lib-dirs: directories (comma or newline separated list)
--extra-lib-dirs=DIR

An extra directory to search for system libraries files.

The command line variant of this flag is --extra-lib-dirs=DIR, which can be specified multiple times.

extra-framework-dirs: directories (comma or newline separated list)
--extra-framework-dirs=DIR

An extra directory to search for frameworks (OS X only).

You might need to use this flag if you have standard system libraries in a non-standard location that is not mentioned in the package’s .cabal file. Using this option has the same affect as appending the directory dir to the extra-lib-dirs field in each library and executable in the package’s .cabal file. The advantage of course is that you do not have to modify the package at all. These extra directories will be used while building the package and for libraries it is also saved in the package registration information and used when compiling modules that use the library.

The command line variant of this flag is --extra-framework-dirs=DIR, which can be specified multiple times.

Profiling options
profiling: boolean
--enable-profiling
--disable-profiling
Since:Cabal 1.21
Default value:False

Build libraries and executables with profiling enabled (for compilers that support profiling as a separate mode). It is only necessary to specify profiling for the specific package you want to profile; cabal new-build will ensure that all of its transitive dependencies are built with profiling enabled.

To enable profiling for only libraries or executables, see library-profiling and executable-profiling.

For useful profiling, it can be important to control precisely what cost centers are allocated; see profiling-detail.

The command line variant of this flag is --enable-profiling and --disable-profiling.

profiling-detail: level
--profiling-detail=level
Since:Cabal 1.23

Some compilers that support profiling, notably GHC, can allocate costs to different parts of the program and there are different levels of granularity or detail with which this can be done. In particular for GHC this concept is called “cost centers”, and GHC can automatically add cost centers, and can do so in different ways.

This flag covers both libraries and executables, but can be overridden by the library-profiling-detail field.

Currently this setting is ignored for compilers other than GHC. The levels that cabal currently supports are:

default
For GHC this uses exported-functions for libraries and toplevel-functions for executables.
none
No costs will be assigned to any code within this component.
exported-functions
Costs will be assigned at the granularity of all top level functions exported from each module. In GHC, this is for non-inline functions. Corresponds to -fprof-auto-exported.
toplevel-functions
Costs will be assigned at the granularity of all top level functions in each module, whether they are exported from the module or not. In GHC specifically, this is for non-inline functions. Corresponds to -fprof-auto-top.
all-functions
Costs will be assigned at the granularity of all functions in each module, whether top level or local. In GHC specifically, this is for non-inline toplevel or where-bound functions or values. Corresponds to -fprof-auto.

The command line variant of this flag is --profiling-detail=none.

library-profiling-detail: level
--library-profiling-detail=level
Since:Cabal 1.23

Like profiling-detail, but applied only to libraries

The command line variant of this flag is --library-profiling-detail=none.

library-vanilla: boolean
--enable-library-vanilla
--disable-library-vanilla
Default value:True

Build ordinary libraries (as opposed to profiling libraries). Mostly, you can set this to False to avoid building ordinary libraries when you are profiling.

The command line variant of this flag is --enable-library-vanilla and --disable-library-vanilla.

library-profiling: boolean
--enable-library-profiling
--disable-library-profiling
Since:Cabal 1.21
Default value:False

Build libraries with profiling enabled. You probably want to use profiling instead.

The command line variant of this flag is --enable-library-profiling and --disable-library-profiling.

executable-profiling: boolean
--enable-executable-profiling
--disable-executable-profiling
Since:Cabal 1.21
Default value:False

Build executables with profiling enabled. You probably want to use profiling instead.

The command line variant of this flag is --enable-executable-profiling and --disable-executable-profiling.

Coverage options
coverage: boolean
--enable-coverage
--disable-coverage
Since:Cabal 1.21
Default value:False

Build libraries and executables (including test suites) with Haskell Program Coverage enabled. Running the test suites will automatically generate coverage reports with HPC.

The command line variant of this flag is --enable-coverage and --disable-coverage.

library-coverage: boolean
--enable-library-coverage
--disable-library-coverage
Deprecated:
Since:Cabal 1.21
Default value:False

Deprecated, use coverage.

The command line variant of this flag is --enable-library-coverage and --disable-library-coverage.

Haddock options

Documentation building support is fairly sparse at the moment. Let us know if it’s a priority for you!

documentation: boolean
--enable-documentation
--disable-documentation
Default value:False

Enables building of Haddock documentation

The command line variant of this flag is --enable-documentation and --disable-documentation.

doc-index-file: templated path
--doc-index-file=TEMPLATE

A central index of Haddock API documentation (template cannot use $pkgid), which should be updated as documentation is built.

The command line variant of this flag is --doc-index-file=TEMPLATE

The following commands are equivalent to ones that would be passed when running setup haddock. (TODO: Where does the documentation get put.)

haddock-hoogle: boolean
Default value:False

Generate a text file which can be converted by Hoogle into a database for searching. This is equivalent to running haddock with the --hoogle flag.

The command line variant of this flag is --hoogle (for the haddock command).

haddock-html: boolean
Default value:True

Build HTML documentation.

The command line variant of this flag is --html (for the haddock command).

haddock-html-location: templated path

Specify a template for the location of HTML documentation for prerequisite packages. The substitutions are applied to the template to obtain a location for each package, which will be used by hyperlinks in the generated documentation. For example, the following command generates links pointing at [Hackage] pages:

html-location: 'http://hackage.haskell.org/packages/archive/$pkg/latest/doc/html'

Here the argument is quoted to prevent substitution by the shell. If this option is omitted, the location for each package is obtained using the package tool (e.g. ghc-pkg).

The command line variant of this flag is --html-location (for the haddock subcommand).

haddock-executables: boolean
Default value:False

Run haddock on all executable programs.

The command line variant of this flag is --executables (for the haddock subcommand).

haddock-tests: boolean
Default value:False

Run haddock on all test suites.

The command line variant of this flag is --tests (for the haddock subcommand).

haddock-benchmarks: boolean
Default value:False

Run haddock on all benchmarks.

The command line variant of this flag is --benchmarks (for the haddock subcommand).

haddock-all: boolean
Default value:False

Run haddock on all components.

The command line variant of this flag is --all (for the haddock subcommand).

haddock-internal: boolean
Default value:False

Build haddock documentation which includes unexposed modules and symbols.

The command line variant of this flag is --internal (for the haddock subcommand).

haddock-css: path

The CSS file that should be used to style the generated documentation (overriding haddock’s default.)

The command line variant of this flag is --css (for the haddock subcommand).

Default value:False

Generated hyperlinked source code using HsColour, and have Haddock documentation link to it.

The command line variant of this flag is --hyperlink-source (for the haddock subcommand).

haddock-hscolour-css: path

The CSS file that should be used to style the generated hyperlinked source code (from HsColour).

The command line variant of this flag is --hscolour-css (for the haddock subcommand).

haddock-contents-location: URL

A baked-in URL to be used as the location for the contents page.

The command line variant of this flag is --contents-location (for the haddock subcommand).

haddock-keep-temp-files: boolean

Keep temporary files.

The command line variant of this flag is --keep-temp-files (for the haddock subcommand).

Advanced global configuration options

http-transport: curl, wget, powershell, or plain-http
--http-transport=transport
Default value:curl

Set a transport to be used when making http(s) requests.

The command line variant of this field is --http-transport=curl.

ignore-expiry: boolean
--ignore-expiry
Default value:False

If True, we will ignore expiry dates on metadata from Hackage.

In general, you should not set this to True as it will leave you vulnerable to stale cache attacks. However, it may be temporarily useful if the main Hackage server is down, and we need to rely on mirrors which have not been updated for longer than the expiry period on the timestamp.

The command line variant of this field is --ignore-expiry.

remote-repo-cache: directory
--remote-repo-cache=DIR
Default value:~/.cabal/packages

[STRIKEOUT:The location where packages downloaded from remote repositories will be cached.] Not implemented yet.

The command line variant of this flag is --remote-repo-cache=DIR.

logs-dir: directory
--logs-dir=DIR
Default value:~/.cabal/logs

[STRIKEOUT:The location where build logs for packages are stored.] Not implemented yet.

The command line variant of this flag is --logs-dir=DIR.

build-summary: template filepath
--build-summary=TEMPLATE
Default value:~/.cabal/logs/build.log

[STRIKEOUT:The file to save build summaries. Valid variables which can be used in the path are $pkgid, $compiler, $os and $arch.] Not implemented yet.

The command line variant of this flag is --build-summary=TEMPLATE.

local-repo: directory
--local-repo=DIR
Deprecated:

[STRIKEOUT:The location of a local repository.] Deprecated. See “Legacy repositories.”

The command line variant of this flag is --local-repo=DIR.

world-file: path
--world-file=FILE
Deprecated:

[STRIKEOUT:The location of the world file.] Deprecated.

The command line variant of this flag is --world-file=FILE.

Undocumented fields: root-cmd, symlink-bindir, build-log, remote-build-reporting, report-planned-failure, one-shot, offline.

Advanced solver options

Most users generally won’t need these.

solver: modular
--solver=modular

This field is reserved to allow the specification of alternative dependency solvers. At the moment, the only accepted option is modular.

The command line variant of this field is --solver=modular.

max-backjumps: nat
--max-backjumps=N
Default value:2000

Maximum number of backjumps (backtracking multiple steps) allowed while solving. Set -1 to allow unlimited backtracking, and 0 to disable backtracking completely.

The command line variant of this field is --max-backjumps=2000.

reorder-goals: boolean
--reorder-goals
--no-reorder-goals
Default value:False

When enabled, the solver will reorder goals according to certain heuristics. Slows things down on average, but may make backtracking faster for some packages. It’s unlikely to help for small projects, but for big install plans it may help you find a plan when otherwise this is not possible. See #1780 for more commentary.

The command line variant of this field is --(no-)reorder-goals.

count-conflicts: boolean
--count-conflicts
--no-count-conflicts
Default value:True

Try to speed up solving by preferring goals that are involved in a lot of conflicts.

The command line variant of this field is --(no-)count-conflicts.

strong-flags: boolean
--strong-flags
--no-strong-flags
Default value:False

Do not defer flag choices. (TODO: Better documentation.)

The command line variant of this field is --(no-)strong-flags.

allow-boot-library-installs: boolean
--allow-boot-library-installs
--no-allow-boot-library-installs
Default value:False

By default, the dependency solver doesn’t allow base, ghc-prim, integer-simple, integer-gmp, and template-haskell to be installed or upgraded. This flag removes the restriction.

The command line variant of this field is --(no-)allow-boot-library-installs.

cabal-lib-version: version
--cabal-lib-version=version

This field selects the version of the Cabal library which should be used to build packages. This option is intended primarily for internal development use (e.g., forcing a package to build with a newer version of Cabal, to test a new version of Cabal.) (TODO: Specify its semantics more clearly.)

The command line variant of this field is --cabal-lib-version=1.24.0.1.

Nix Integration

Nix is a package manager popular with some Haskell developers due to its focus on reliability and reproducibility. cabal now has the ability to integrate with Nix for dependency management during local package development.

Enabling Nix Integration

To enable Nix integration, simply pass the --enable-nix global option when you call cabal. To use this option everywhere, edit your $HOME/.cabal/config file to include:

nix: True

If the package (which must be locally unpacked) provides a shell.nix or default.nix file, this flag will cause cabal to run most commands through nix-shell. If both expressions are present, shell.nix is preferred. The following commands are affected:

  • cabal configure
  • cabal build
  • cabal repl
  • cabal install (only if installing into a sandbox)
  • cabal haddock
  • cabal freeze
  • cabal gen-bounds
  • cabal run

If the package does not provide an expression, cabal runs normally.

Creating Nix Expressions

The Nix package manager is based on a lazy, pure, functional programming language; packages are defined by expressions in this language. The fastest way to create a Nix expression for a Cabal package is with the cabal2nix tool. To create a shell.nix expression for the package in the current directory, run this command:

$ cabal2nix --shell ./. >shell.nix

Nix Expression Evaluation

(This section describes for advanced users how Nix expressions are evaluated.)

First, the Nix expression (shell.nix or default.nix) is instantiated with nix-instantiate. The --add-root and --indirect options are used to create an indirect root in the Cabal build directory, preventing Nix from garbage collecting the derivation while in use. The IN_NIX_SHELL environment variable is set so that builtins.getEnv works as it would in nix-shell.

Next, the commands above are run through nix-shell using the instantiated derivation. Again, --add-root and --indirect are used to prevent Nix from garbage collecting the packages in the environment. The child cabal process reads the CABAL_IN_NIX_SHELL environment variable to prevent it from spawning additional child shells.

Further Reading

The Nix manual provides further instructions for writing Nix expressions. The Nixpkgs manual describes the infrastructure provided for Haskell packages.