Dynamic Linking - acowley/roshask GitHub Wiki

Dynamic linking is still a feature-in-progress with GHC (this article reflects the state of affairs for GHC 7.6.1 on Linux), but it can bring very pleasant benefits: faster linking and smaller executables. For example, if I build roshask's Turtle example project with static linking, I get a Turtle executable that is almost 16MB. If I build it with dynamic linking, the executable is just under 50KB. So what's the catch? First, all your Haskell libraries must be installed with sharing enabled. This can be set in your ~/.cabal/config file by setting the option shared: True. You might also set executable-dynamic: True, but GHC imposes some limitations on dynamic linking. The example module Turtle3.hs, for example, makes use of Template Haskell via a logging statement. To support this, GHC requires that you first build your program with static linking, then build with dynamic linking making sure that the object files produced by the two builds are distinct.

The upshot is this, if you have executable-dynamic: True set in ~/.cabal/config, then you must first build with

cabal configure --disable-executable-dynamic && cabal build

then build with

cabal configure --ghc-options="-osuf s_o" && cabal build

The first step produces regular .o object files that are used by TemplateHaskell when building a new set of .s_o object files before finally producing a tiny executable. Hopefully this situation will improve in the future!