20

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...

  1. Which preprocessor definitions can I use to switch between platforms?

  2. 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.

Rehno Lindeque
  • 4,236
  • 2
  • 23
  • 31

1 Answers1

13
  1. 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

  2. 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.

Secoe
  • 634
  • 4
  • 12
  • 7
    It is preferred to use os_HOST_OS to include different packages, rather than using CPP, if possible. – Don Stewart Dec 10 '12 at 14:53
  • 4
    You can also use cabal's `os` blocks to choose between entire source trees if there are whole modules that need to be written differently for different operating systems. Instead of putting a `cpp-options` block inside, but a `hs-source-dirs` block inside. – Daniel Wagner Dec 10 '12 at 15:09