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

1

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.

Leverrier answered 10/12, 2012 at 10:35 Comment(0)
M
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.

Mycostatin answered 10/12, 2012 at 14:20 Comment(2)
It is preferred to use os_HOST_OS to include different packages, rather than using CPP, if possible.Holmann
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.Ferrari

© 2022 - 2024 — McMap. All rights reserved.