How to write platform-independent code in Haskell (ghc)

haskell, platform-independent, platform-specific

Solution

Take a look at the `os_HOST_OS` flags in combination with the C preprocessor option `-cpp` (or using `{-# LANGUAGE CPP #-}`) as stated in the GHC documentation

Add `extensions: CPP` to your package description as shown in the Cabal documentation and define a custom flag like this:

if os(linux)
     cpp-options: -DINOTIFY
if os(darwin)
     cpp-options: -DKQUEUE

You can then use `#ifdef` in your source.

Problem

There are a few platform-specific libraries in Hackage that I'd like to use (e.g. inotify, kqueue). However, documentation on how to switch between platforms using conditional compilation seems a little bit sparse. I'm having some trouble finding the relevant docs... Which preprocessor definitions can I use to switch between platforms? How can I set up my cabal file to include/exclude inotify/kqueue on linux/osx respectively? I hope that having it documented here might be useful for others too, so it may be worthwhile to mention other common platforms. It's silly to look for this stuff all over the place.

Original source