2
votes

On Arch Linux, installed Haskell libraries are dynamically linked by default. So to make anything compile in ghc, I have to use the -dynamic flag, otherwise it doesn't even discover the libraries. However, I would like to produce statically linked binaries that I can distribute to other systems.

Is there any way to produce a statically linked binary from dynamic/shared libraries with ghc?

I tried -optl-static from this related post but that led to countless "undefined reference" errors.

2
Isn't cabal v2-build default to static linking?arrowd
It seems this question is not GHC/Haskell specific - the question is, how to statically link against a dynamic library? My default answer would be that this is not possible. A solution would be to embed the dylibs in the executable, using something like AppImage on Linux or windres on Windows, but I don't know how you'd tell cabal/the linker to find them there.Ari Fordsham

2 Answers

1
votes

Libraries compiled for dynamic linking are missing information needed for static linking (and vice versa). For details, see:

This is intrinsic in the design of the OS linker, and beyond any limitation of cabal or GHC. For example, this cannot be simply done in C either.

To achieve single-file redistributable binaries, you could try bundling the dynamic libs into the executable, using a format such as AppImage on Linux, or the windres resource scheme on Windows, but you would have to manually set up your code and cabal to find the libraries in the right place.

0
votes

If you use The Stack build system, it will automatically download and manage a fixed version of GHC and all libraries per project (and store them in a hidden folder in your project directory), so if you get it set up right, the whole lot will be static. Stack doesn't have amazing static support right now, but it can be made to work. Some resources: