Joshua Chia
Joshua Chia

Reputation: 1968

How do I get stack to use dynamic linking?

I'm using stack to build projects and find that the generated executables are pretty large (10M) even for simple programs. In order to reduce the executable size, how can i get stack to build shared libraries and generate executables that dynamically link to shared libraries?

Upvotes: 12

Views: 2740

Answers (1)

Steven Shaw
Steven Shaw

Reputation: 6249

Add '-dynamic' to ghc-options in your .cabal file.

For example, in a project generated by stack new simple-example simple, the simple executable was 1.0M before adding '-dynamic' to ghc-options. It reduced to 12K after the change.

Here's the relevant part of the simple-example.cabal:

executable simple-example
  hs-source-dirs:      src
  main-is:             Main.hs
  default-language:    Haskell2010
  build-depends:       base >= 4.7 && < 5
  ghc-options:         -dynamic

Build with stack build (no options are required).

To show which libraries it's dynamically linked against, you can use the ldd tool (or otool -L on Mac).

$ otool -L .stack-work/install/x86_64-osx/lts-6.10/7.10.3/bin/simple-example
.stack-work/install/x86_64-osx/lts-6.10/7.10.3/bin/simple-example:
        @rpath/libHSbase-4.8.2.0-HQfYBxpPvuw8OunzQu6JGM-ghc7.10.3.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libHSinteger-gmp-1.0.0.0-2aU3IZNMF9a7mQ0OzsZ0dS-ghc7.10.3.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libHSghc-prim-0.4.0.0-8TmvWUcS1U1IKHT0levwg3-ghc7.10.3.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libHSrts-ghc7.10.3.dylib (compatibility version 0.0.0, current version 0.0.0)
        @rpath/libffi.dylib (compatibility version 7.0.0, current version 7.2.0)
        /usr/lib/libiconv.2.dylib (compatibility version 7.0.0, current version 7.0.0)
        /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1226.10.1)

Upvotes: 9

Related Questions