How do I use cabal's MIN_VERSION_ and other macros with ghci?

cabal, ghci, haskell

Solution

Nowadays, `cabal` supports a `cabal repl` subcommand, which does all the setup for you, so at least for `ghci` the following is unnecessary. Nevertheless:

The `cabal build` command generates the file `dist/build/autogen/cabal_macros.h`, which contains all the definitions you need. In order to include that file in a ghc invocation, you'll need the flags `-optP-include -optPdist/build/autogen/cabal_macros.h`.

For convenience, you can place the following in a `.ghci` file in the project directory:

:set -optP-include -optPdist/build/autogen/cabal_macros.h

so that you don't have to type out the options every time you want to use ghci.

Beware, though: the macros will be defined according to the configuration when you last ran `cabal build`, and will not be updated when you install new packages or use a different GHC version: for that you'd need to re-configure and rebuild the package.

(Thanks to Simon Hengel on the libraries list for this wisdom: http://www.haskell.org/pipermail/libraries/2012-September/018491.html).

Problem

When I use Cabal's various `MIN_VERSION_` macros in a Haskell project, how can I ensure they are all correctly defined when I am not using cabal, e.g. when testing in GHCi?

Original source