Personal tools

GHC/FAQ

From HaskellWiki

< GHC(Difference between revisions)
Jump to: navigation, search
(+cat)
(Why does linking take so long?: dynamic linking)
 
(28 intermediate revisions by 18 users not shown)
Line 4: Line 4:
 
This page is rather long. We've started to add some sub-headings, but would welcome your help in making it better organised.
 
This page is rather long. We've started to add some sub-headings, but would welcome your help in making it better organised.
   
= GHC on particular platforms =
+
= GHC (Platform-specific Issues) =
   
== How do I port GHC to platform X? ==
+
== Porting GHC ==
  +
  +
=== How do I port GHC to platform X? ===
   
 
There are two distinct possibilities: either
 
There are two distinct possibilities: either
Line 16: Line 16:
 
Both ways require you to bootstrap from intermediate HC files: these are the stylised C files generated by GHC when it compiles Haskell source. Basically the idea is to take the HC files for GHC itself to the target machine and compile them with gcc to get a working GHC, and go from there.
 
Both ways require you to bootstrap from intermediate HC files: these are the stylised C files generated by GHC when it compiles Haskell source. Basically the idea is to take the HC files for GHC itself to the target machine and compile them with gcc to get a working GHC, and go from there.
   
The [http://www.haskell.org/ghc/docs/latest/html/building Building Guide] has all the details on how to bootstrap GHC on a new platform.
+
The [http://hackage.haskell.org/trac/ghc/wiki/Building Building Guide] has all the details on how to bootstrap GHC on a new platform.
   
   
== GHC on Linux ==
+
== Linux-related ==
   
=== I Can't run GHCi on Linux, because it complains about a missing <tt>libreadline.so.3</tt>. ===
+
=== Missing libreadline.so.x Errors ===
   
The "correct" fix for this problem is to install the correct RPM for the particular flavour of Linux on your machine. If this isn't an option, however, there is a hack that might work: make a symbolic link from <tt>libreadline.so.4</tt> to <tt>libreadline.so.3</tt> in <tt>/usr/lib</tt>. We tried this on a SuSE 7.1 box and it seemed to work, but YMMV.
+
==== I Can't run GHCi on Linux, because it complains about a missing <tt>libreadline.so.3</tt>. ====
   
=== Linking a program causes the following error on Linux: <tt>/usr/bin/ld: cannot open -lgmp: No such file or directory</tt> ===
+
The "correct" fix for this problem is to install the correct package for the particular flavour of Linux on your machine. If this isn't an option, however, there is a hack that might work: make a symbolic link from <tt>libreadline.so.4</tt> to <tt>libreadline.so.3</tt> in <tt>/usr/lib</tt>. We tried this on a SuSE 7.1 box and it seemed to work, but YMMV.
  +
  +
=== Linking Errors ===
  +
  +
==== Linking a program causes the following error on Linux: <tt>/usr/bin/ld: cannot open -lgmp: No such file or directory</tt> ====
   
 
The problem is that your system doesn't have the GMP library installed. If this is a RedHat distribution, install the RedHat-supplied gmp-devel package, and the gmp package if you don't already have it. There have been reports that installing the RedHat packages also works for SuSE (SuSE doesn't supply a shared gmp library).
 
The problem is that your system doesn't have the GMP library installed. If this is a RedHat distribution, install the RedHat-supplied gmp-devel package, and the gmp package if you don't already have it. There have been reports that installing the RedHat packages also works for SuSE (SuSE doesn't supply a shared gmp library).
   
=== GHC and SELinux ===
+
=== SELinux-related ===
  +
  +
==== Memory Allocation Errors ====
   
 
If you have SELinux enabled on your system, then GHC may fail with a memory allocation error:
 
If you have SELinux enabled on your system, then GHC may fail with a memory allocation error:
Line 50: Line 50:
 
<tt>/usr/bin/chcon -t unconfined_execmem_exec_t /path/to/binary/prog</tt>
 
<tt>/usr/bin/chcon -t unconfined_execmem_exec_t /path/to/binary/prog</tt>
   
== GHC on Solaris ==
+
== Solaris-related ==
=== Solaris users may sometimes get link errors due to libraries needed by GNU Readline. ===
+
  +
=== Link Errors ===
  +
  +
==== Solaris users may sometimes get link errors due to libraries needed by GNU Readline. ====
   
 
We suggest you try linking in some combination of the termcap, curses and ncurses libraries, by giving <tt>-ltermcap</tt>, <tt>-lcurses</tt> and <tt>-lncurses</tt> respectively. If you encounter this problem, we would appreciate feedback on it, since we don't fully understand what's going on here.
 
We suggest you try linking in some combination of the termcap, curses and ncurses libraries, by giving <tt>-ltermcap</tt>, <tt>-lcurses</tt> and <tt>-lncurses</tt> respectively. If you encounter this problem, we would appreciate feedback on it, since we don't fully understand what's going on here.
Line 58: Line 58:
 
It has been reported that if you have multiple versions of the readline library installed on Linux, then this may cause the build to fail. If you have multiple versions of readline, try uninstalling all except the most recent version.
 
It has been reported that if you have multiple versions of the readline library installed on Linux, then this may cause the build to fail. If you have multiple versions of readline, try uninstalling all except the most recent version.
   
== GHC on Windows ==
+
== Windows-related ==
=== My program that uses a really large heap crashes on Windows. ===
 
   
For utterly horrible reasons, programs that use more than 128Mb of heap won't work when compiled dynamically on Windows (they should be fine statically compiled).
+
=== Heapsize-related Crashes ===
   
=== I can't use readline under GHCi on Windows ===
+
==== My program that uses a really large heap crashes on Windows. ====
   
In order to load the readline package under GHCi on Windows, you need to make a version of the readline library that GHCi can load. Instructions for GHC 6.2.2. are here.
+
For utterly horrible reasons, programs that use more than 128Mb of heap won't work when compiled dynamically on Windows (they should be fine statically compiled).
   
=== Ctrl-C doesn't work on Windows ===
+
=== Ctrl-C Not Working ===
   
 
When running GHC under a Cygwin shell on Windows, Ctrl-C sometimes doesn't work. A workaround is to use Ctrl-Break instead. Another workaround is to use the rlwrap program (cygwin package available) to invoke ghci : In addition to proper Ctrl-C, you also get emacs (or vi) key bindings and command history across sessions.
 
When running GHC under a Cygwin shell on Windows, Ctrl-C sometimes doesn't work. A workaround is to use Ctrl-Break instead. Another workaround is to use the rlwrap program (cygwin package available) to invoke ghci : In addition to proper Ctrl-C, you also get emacs (or vi) key bindings and command history across sessions.
   
=== How do I link Haskell with C++ code compiled by Visual Studio? ===
+
=== Linking with Visual Studio C++ Code ===
   
==== Prerequisites ====
+
==== How do I link Haskell with C++ code compiled by Visual Studio? ====
  +
  +
===== Prerequisites =====
   
 
It is assumed that the reader is familiar with the Haskell
 
It is assumed that the reader is familiar with the Haskell
Line 78: Line 78:
 
and is able to compile Haskell programs with GHC and C++ programs with Visual Studio.
 
and is able to compile Haskell programs with GHC and C++ programs with Visual Studio.
   
==== Background ====
+
===== Background =====
   
 
GHC has two modes of code generation. It either compiles Haskell straight into object code
 
GHC has two modes of code generation. It either compiles Haskell straight into object code
Line 94: Line 94:
 
all source files (Haskell and C++) on the command line of GHC.
 
all source files (Haskell and C++) on the command line of GHC.
   
==== Invoking a Haskell DLL from a C++ executable ====
+
===== Invoking a Haskell DLL =====
  +
  +
====== From a C++ executable ======
   
 
#Make a Haskell DLL as explained in [http://www.haskell.org/ghc/docs/latest/html/users_guide/win32-dlls.html#win32-dlls-foreign]
 
#Make a Haskell DLL as explained in [http://www.haskell.org/ghc/docs/latest/html/users_guide/win32-dlls.html#win32-dlls-foreign]
Line 101: Line 101:
 
#Link the C++ program against the import library.
 
#Link the C++ program against the import library.
   
==== Invoking a C++ DLL from a Haskell executable ====
+
====== From a Haskell executable ======
   
 
#Make a DLL project in Visual Studio. It will create a <tt>.vcproj</tt> and <tt>.sln</tt> files for you. Add your C++ source files to this project.
 
#Make a DLL project in Visual Studio. It will create a <tt>.vcproj</tt> and <tt>.sln</tt> files for you. Add your C++ source files to this project.
Line 108: Line 108:
 
#Link your Haskell project, adding the library:<tt><br>ghc --make main.hs -optl-lMyDLL -optl-L.<br></tt>''mind the dot at the end of the command line!''<br> (<tt>[http://www.haskell.org/ghc/docs/latest/html/users_guide/options-phases.html#forcing-options-through -optl]</tt> switch passes its argument as an option to the linker).
 
#Link your Haskell project, adding the library:<tt><br>ghc --make main.hs -optl-lMyDLL -optl-L.<br></tt>''mind the dot at the end of the command line!''<br> (<tt>[http://www.haskell.org/ghc/docs/latest/html/users_guide/options-phases.html#forcing-options-through -optl]</tt> switch passes its argument as an option to the linker).
   
== Why isn't GHC available for .NET? ==
+
=== GHCi Hanging Issues ===
   
  +
==== GHCi hangs after "Loading package base ... linking ... done." ====
   
It would make a lot of sense to give GHC a .NET back end, and it's a
+
On a small number of systems GHCi will fail to start, hanging after loading the base package. The "Prelude>" prompt is never reached.
  +
  +
This is believed to be due to a bug in Windows thought to affect tablet PCs, although the details are not fully understood.
  +
  +
A workaround is to open a command prompt, enter "chcp 28591" - if this hangs hit Ctrl-C - and then run "ghci". Some users may find this [http://support.microsoft.com/kb/925271 hotfix] useful.
  +
  +
=== A console window opens when my application is supposed to be GUI only ===
  +
  +
Windows has several different "subsystems", the default subsystem which the mingw linker uses is console, so that stdout/stderr can be printed on screen and stdin be read from the console window.
  +
  +
This can be solved by giving the option -optl-mwindows with the compile command:
  +
ghc --make -optl-mwindows MyProgramWithGUI.lhs
  +
With this option, the option -mwindows is passed to the linker.
  +
  +
Caveat: attempting to read from stdin with -mwindows set may cause a runtime error, any output on stdout/stderr will be lost.
  +
  +
== .NET/JVM Availability ==
  +
  +
=== Why isn't GHC available for .NET or on the JVM? ===
  +
  +
It would make a lot of sense to give GHC a .NET or JVM back end, and it's a
 
question that comes up regularly. The reason that we haven't done it
 
question that comes up regularly. The reason that we haven't done it
 
here, at GHC HQ, is because it's a more substantial undertaking than
 
here, at GHC HQ, is because it's a more substantial undertaking than
Line 122: Line 123:
 
we would love to see it done. There is some good groundwork already done:
 
we would love to see it done. There is some good groundwork already done:
   
* Sigbjorn Finne did a simple interop implementation that allows a Haskell program to be compiled to native code (as now) but to call .NET programs via a variant of the FFI. I don't think this work is in active use, and I'd be surprised if it worked out of the box, but it could probably be revived with modest effort
+
* Ashley Yakeley worked on a [http://sourceforge.net/projects/jvm-bridge/ Haskell-JVM bridge]
  +
  +
* Sigbjorn Finne did a simple interop implementation ([http://hackage.haskell.org/package/hs-dotnet the hs-dotnet package]) that allows a Haskell program to be compiled to native code (as now) but to call .NET programs via a variant of the FFI. I don't think this work is in active use, and I'd be surprised if it worked out of the box, but it could probably be revived with modest effort
   
 
* Andre Santos and his colleagues at UFPE in Brazil are working on a .NET back end, that generates CLR IL, though I don't know where they are up to.
 
* Andre Santos and his colleagues at UFPE in Brazil are working on a .NET back end, that generates CLR IL, though I don't know where they are up to.
Line 129: Line 130:
   
 
* GHC.Net would be extra attractive if there was a Visual Studio integration for GHC. Substantial progress on this has been made in 2004 by Simon Marlow, Krasimir Angelov, and Andre Santos and colleagues.
 
* GHC.Net would be extra attractive if there was a Visual Studio integration for GHC. Substantial progress on this has been made in 2004 by Simon Marlow, Krasimir Angelov, and Andre Santos and colleagues.
  +
  +
* Brian Alliet created a patch for GHC called LambdaVM that compiles programs into JVM bytecode. [http://wiki.brianweb.net/LambdaVM/LambdaVM]
  +
  +
* Not GHC but [[UHC]]: the Jazy backend of UHC generates Java class files to allow Haskell programs to run on the Java Virtual Machine (JVM). Jazy is [http://www.cs.uu.nl/wiki/bin/view/Ehc/UhcJazyDocumentation#2_Status not fully functional yet].
  +
   
 
There may be others that I don't know of. If anyone wants to join in
 
There may be others that I don't know of. If anyone wants to join in
 
this effort, do contact the above folk. And please keep us informed!
 
this effort, do contact the above folk. And please keep us informed!
   
Here's a summary of why it's a non-trivial thing to do:
+
Here's a summary of why it's a non-trivial thing to do (using .NET language, but it mostly applies to the JVM too):
   
* The first thing is to generate native CLR Intermediate Language (IL). That's not really hard. Requires thinking about representations for thunks and functions, and it may not be particularly efficient, but it can surely be done. An open question is about whether to generate verifiable IL or not. The trouble here is that Haskell's type system is more expressive than the CLR's in some ways, notably the use of higher-kinded type variables. So, to generate verifiable IL one is bound to need some run-time casts, and it's not clear how to minimise these.
+
* The first thing is to generate native CLR Intermediate Language (IL). That's not really hard. Requires thinking about representations for thunks and functions, and it may not be particularly efficient, but it can surely be done.
  +
: An open question is about whether to generate ''verifiable'' IL or not. The trouble here is that Haskell's type system is more expressive than the CLR's in some ways, notably the use of higher-kinded type variables. So, to generate verifiable IL one is bound to need some run-time casts, and it's not clear how to minimise these.
   
At first blush this is *all* you need do. But it isn't!
+
At first blush this is ''all'' you need do. But it isn't!
   
 
* Next, you need to think about how to inter-operate with .NET libraries. You don't really want to write "foreign import..." for each and every import. You'd like GHC to read the CLR meta-data directly. But there are lots of tricky issues here; see the paper that Mark Shields and I wrote about "Object-oriented style overloading for Haskell".
 
* Next, you need to think about how to inter-operate with .NET libraries. You don't really want to write "foreign import..." for each and every import. You'd like GHC to read the CLR meta-data directly. But there are lots of tricky issues here; see the paper that Mark Shields and I wrote about "Object-oriented style overloading for Haskell".
  +
  +
* A closely-related question is this: how to make the type systems of Java/.NET and Haskell "line up"? For example, when importing a Java procedure, what is the Haskell type that corresponds to its .NET/JVM type? How do you sub-class a .NET class in Haskell? For example [http://research.microsoft.com/en-us/um/people/simonpj/papers/oo-haskell/index.htm Object-Oriented Style Overloading for Haskell] gives one "take" on the subject, but there are plenty of other possibilities.
   
 
* Now you need to figure out how to implement GHC's primitive operations:
 
* Now you need to figure out how to implement GHC's primitive operations:
* the I/O monad
+
** the I/O monad
* arbitrary precision arithmetic
+
** arbitrary precision arithmetic
* concurrency
+
** concurrency
* exceptions
+
** exceptions
* finalisers
+
** finalisers
* stable pointers
+
** stable pointers
* [[Software transactional memory]]
+
** [[Software transactional memory]]
   
Not all of these are necessary, of course, but many are used in the libraries. The CLR supports many of them (e.g. concurrency) but with a very different cost model.
+
:: Not all of these are necessary, of course, but many are used in the libraries. The CLR supports many of them (e.g. concurrency) but with a very different cost model.
   
 
* Last, you have to figure out what to do for the libraries. GHC has a pretty large library, and you either have to implement the primops on which the library is based (see previous point), or re-implement it. For example, GHC's implementation of I/O uses mutable state, concurrency, and more besides. For each module, you need to decide either to re-implement it using .NET primitives, or to implement the stuff the module is based on.
 
* Last, you have to figure out what to do for the libraries. GHC has a pretty large library, and you either have to implement the primops on which the library is based (see previous point), or re-implement it. For example, GHC's implementation of I/O uses mutable state, concurrency, and more besides. For each module, you need to decide either to re-implement it using .NET primitives, or to implement the stuff the module is based on.
Line 157: Line 165:
 
production quality implementation that runs a substantial majority of
 
production quality implementation that runs a substantial majority of
 
Haskell programs "out of the box" requires a decent stab at all of them.
 
Haskell programs "out of the box" requires a decent stab at all of them.
  +
  +
== Mac OS X-related ==
  +
  +
=== Linking with GHC ===
  +
  +
==== Linking with ghc produces <tt>ld: Undefined symbols: _sprintf$LDBLStub ...</tt> ====
  +
  +
This happens on a PowerPC Mac OS X 10.4 if gcc-3.3 is the default compiler and you try to compile with a ghc that has been built with gcc-4.0. For example:
  +
  +
$ cat t2.hs
  +
module Main where
  +
main = putStr ("t2: Hello trac 1066 2007-Feb-17 19.48\n")
  +
$ gcc --version
  +
gcc (GCC) 3.3 20030304 (Apple Computer, Inc. build 1819)
  +
...
  +
$ ghc --make t2.hs
  +
[1 of 1] Compiling Main ( t2.hs, t2.o )
  +
Linking t2 ...
  +
ld: Undefined symbols:
  +
_sprintf$LDBLStub
  +
_fprintf$LDBLStub
  +
_vfprintf$LDBLStub
  +
_sscanf$LDBLStub
  +
$
  +
  +
To correct this, set the default compiler to gcc-4.0 (<tt>sudo gcc_select 4.0</tt>) or include linking options <tt>-lHSrts -lSystemStubs</tt> in that order on the ghc command:
  +
  +
$ ghc --make t2.hs -lHSrts -lSystemStubs
  +
[1 of 1] Skipping Main ( t2.hs, t2.o )
  +
Linking t2 ...
  +
$
  +
  +
The command
  +
  +
for l in <ghc installation directory>/lib/ghc-<ghc version>/*.a; do nm $l 2>&1 | if grep LDBLStub 1>/dev/null; then echo $l; fi; done
  +
  +
prints the list of libraries that may be needed instead of or in addition to <tt>-lHSrts</tt> before <tt>-lSystemStubs</tt> on the ghc command. For example:
  +
  +
$ for l in /Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/*.a; do nm $l 2>&1 | if grep LDBLStub 1>/dev/null; then echo $l; fi; done
  +
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSX11_cbits.a
  +
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts.a
  +
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_debug.a
  +
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_p.a
  +
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_thr.a
  +
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_thr_debug.a
  +
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_thr_p.a
  +
$
  +
  +
[http://hackage.haskell.org/trac/ghc/ticket/1066] has additional details.
  +
  +
=== Linking with C++ ===
  +
  +
==== Linking with a C++ library gives: <tt>Undefined symbols: __Unwind_Resume</tt> ====
  +
  +
You need to pass the <tt>-fexceptions</tt> to the linker. Use <tt>-optl -fexceptions</tt>.
   
 
---------------------------------------
 
---------------------------------------
 
= Running GHC =
 
= Running GHC =
   
== GHC doesn't like filenames containing +. ==
+
== Filenames Containing '+' ==
  +
  +
=== GHC doesn't like filenames containing '+'. ===
   
 
Indeed not. You could change <tt>+</tt> to <tt>p</tt> or <tt>plus</tt>.
 
Indeed not. You could change <tt>+</tt> to <tt>p</tt> or <tt>plus</tt>.
   
== Why does linking take so long? ==
+
== Linking ==
  +
  +
=== Why does linking take so long? ===
   
 
Linking a small program should take no more than a few seconds. Larger programs can take longer, but even linking GHC itself only takes 3-4 seconds on our development machines.
 
Linking a small program should take no more than a few seconds. Larger programs can take longer, but even linking GHC itself only takes 3-4 seconds on our development machines.
Line 171: Line 234:
 
Long link times have been attributed to using Sun's linker on Solaris, as compared to GNU ld which appears to be much faster. So if you're on a Sun box, try switching to GNU ld. [http://www.haskell.org/pipermail/glasgow-haskell-users/2002-November/004477.html This article] from the mailing list has more information.
 
Long link times have been attributed to using Sun's linker on Solaris, as compared to GNU ld which appears to be much faster. So if you're on a Sun box, try switching to GNU ld. [http://www.haskell.org/pipermail/glasgow-haskell-users/2002-November/004477.html This article] from the mailing list has more information.
   
== Why do I get errors about missing include files when compiling with -O or -prof? ==
+
One huge slowdown is also working on remote filesystem, e.g., nfs.
  +
Work on a local machine, preferably.
   
Certain options, such as -O, turn on via-C compilation, instead of using the native code generator. Include files named by -#include options or in foreign import declarations are only used in via-C compilation mode. See [http://www.haskell.org/ghc/docs/latest/html/users_guide/sec-ffi-ghc.html#finding-header-files Section 8.2.2.1, ´Finding Header files¡] for more details.
+
You may also speed up linking by enabling dynamic linking with the <code>-dynamic</code> option of GHC or <code>--enable-executable-dynamic</code> of [[Cabal]].
   
== How do I compile my program for profiling without overwriting the object files and hi files I've already built? ==
+
== Missing Include Files ==
  +
  +
=== Why do I get errors about missing include files when compiling with -O or -prof? ===
  +
  +
Certain options, such as -O, turn on via-C compilation, instead of using the native code generator. Include files named by -#include options or in foreign import declarations are only used in via-C compilation mode. See [http://www.haskell.org/ghc/docs/latest/html/users_guide/sec-ffi-ghc.html#finding-header-files Section 8.2.2.1, ´Finding Header files] for more details.
  +
  +
== Compiling for Profiling ==
  +
  +
=== How do I compile my program for profiling without overwriting the object files and hi files I've already built? ===
   
 
You can select alternative suffixes for object files and interface files, so you can have several builds of the same code coexisting in the same directory. For example, to compile with profiling, you might do this:
 
You can select alternative suffixes for object files and interface files, so you can have several builds of the same code coexisting in the same directory. For example, to compile with profiling, you might do this:
Line 183: Line 246:
 
</pre>
 
</pre>
   
See [http://www.haskell.org/ghc/docs/latest/html/users_guide/separate-compilation.html#options-output Section 4.6.4, ´Redirecting the compilation output(s)¡] for more details on the <tt>-osuf</tt> and <tt>-hisuf</tt> options.
+
See [http://www.haskell.org/ghc/docs/latest/html/users_guide/separate-compilation.html#options-output Section 4.6.4, ´Redirecting the compilation output(s)] for more details on the <tt>-osuf</tt> and <tt>-hisuf</tt> options.
   
 
---------------------------------------
 
---------------------------------------
 
= Syntax =
 
= Syntax =
   
== I can't get string gaps to work ==
+
== String Gaps ==
   
If you're also using CPP, beware of the known pitfall with string gaps mentioned in [http://www.haskell.org/ghc/docs/latest/html/users_guide/options-phases.html#cpp-string-gaps Section 4.10.3.1, CPP and string gaps¡].
+
=== I can't get string gaps to work ===
  +
  +
If you're also using CPP, beware of the known pitfall with string gaps mentioned in [http://www.haskell.org/ghc/docs/latest/html/users_guide/options-phases.html#cpp-string-gaps Section 4.10.3.1, CPP and string gaps].
   
 
---------------------------------------
 
---------------------------------------
 
= GHCi =
 
= GHCi =
   
== GHCi complains about missing symbols like CC_LIST when loading a previously compiled .o file. ==
+
== Error Messages ==
  +
  +
=== Missing Symbols ===
  +
  +
==== GHCi complains about missing symbols like CC_LIST when loading a previously compiled .o file. ====
   
 
This probably means the .o files in question were compiled for profiling (with -prof). Workaround: recompile them without profiling. We really ought to detect this situation and give a proper error message.
 
This probably means the .o files in question were compiled for profiling (with -prof). Workaround: recompile them without profiling. We really ought to detect this situation and give a proper error message.
   
== When I try to start ghci (probably one I compiled myself) it says <tt>ghc-5.02: not built for interactive use</tt> ==
+
=== Starting GHCi ===
   
  +
==== When I try to start ghci (probably one I compiled myself) it says <tt>ghc-5.02: not built for interactive use</tt> ====
 
To build a working ghci, you need to build GHC 5.02 with itself; the above message appears if you build it with 4.08.X, for example. It'll still work fine for batch-mode compilation, though. Note that you really must build with exactly the same version of the compiler. Building 5.02 with 5.00.2, for example, may or may not give a working interactive system; it probably won't, and certainly isn't supported. Note also that you can build 5.02 with any older compiler, back to 4.08.1, if you don't want a working interactive system; that's OK, and supported.
 
To build a working ghci, you need to build GHC 5.02 with itself; the above message appears if you build it with 4.08.X, for example. It'll still work fine for batch-mode compilation, though. Note that you really must build with exactly the same version of the compiler. Building 5.02 with 5.00.2, for example, may or may not give a working interactive system; it probably won't, and certainly isn't supported. Note also that you can build 5.02 with any older compiler, back to 4.08.1, if you don't want a working interactive system; that's OK, and supported.
   
== I get an error message from GHCi about a "<tt>duplicate definition for symbol __module_registered</tt>" ==
+
=== Duplicate Definitions ===
  +
  +
==== I get an error message from GHCi about a "<tt>duplicate definition for symbol __module_registered</tt>" ====
   
 
An error message like this:
 
An error message like this:
Line 215: Line 279:
   
 
probably indicates that when building a library for GHCi (<tt>HSfgl.o</tt> in the above example), you should use the <tt>-x</tt> option to <tt>ld</tt>.
 
probably indicates that when building a library for GHCi (<tt>HSfgl.o</tt> in the above example), you should use the <tt>-x</tt> option to <tt>ld</tt>.
  +
  +
== REPL Workarounds ==
  +
  +
=== Why doesn't "x=1" work at the ghci prompt? ===
  +
  +
Type
  +
<pre>
  +
let x = 1
  +
</pre>
  +
  +
instead.
  +
  +
From IRC: "But in general, it's tricky to define function interactively. You can do simple stuff easily enough: "let f x = x * x" or whatever; but for anything other than a simple one-liner, I usually stick it into a file and then load it with ghci.
   
 
---------------------------------------
 
---------------------------------------
 
= The Foreign Function Interface =
 
= The Foreign Function Interface =
   
== When do other Haskell threads get blocked by an FFI call? ==
+
== Blocking ==
  +
  +
=== When do other Haskell threads get blocked by an FFI call? ===
   
 
{| border="1" align="center"
 
{| border="1" align="center"
Line 243: Line 320:
 
There used to be another modifier, <tt>threadsafe</tt>, which is now deprecated. Use `safe` instead.
 
There used to be another modifier, <tt>threadsafe</tt>, which is now deprecated. Use `safe` instead.
   
== When I use a foreign function that takes or returns a float, it gives the wrong answer, or crashes. ==
+
== Using Floats ==
  +
  +
=== When I use a foreign function that takes or returns a float, it gives the wrong answer, or crashes. ===
  +
  +
You should use the <tt>-#include</tt> option to bring the correct prototype into scope (see [http://www.haskell.org/ghc/docs/latest/html/users_guide/options-phases.html#options-C-compiler Section 4.10.5, ´Options affecting the C compiler (if applicable)]).
   
You should use the <tt>-#include</tt> option to bring the correct prototype into scope (see [http://www.haskell.org/ghc/docs/latest/html/users_guide/options-phases.html#options-C-compiler Section 4.10.5, ´Options affecting the C compiler (if applicable)¡]).
+
== Propogating Run-time Errors as Exceptions ==
   
== How can I propagate a Haskell run-time error (e.g. pattern match failure) as an exception to a foreign caller of the Haskell function. ==
+
=== How can I propagate a Haskell run-time error (e.g. pattern match failure) as an exception to a foreign caller of the Haskell function. ===
   
 
If a runtime error occurs inside a DLL compiled by ghc (like
 
If a runtime error occurs inside a DLL compiled by ghc (like
Line 266: Line 343:
 
foreign export, translating an error code into the C++ exception.
 
foreign export, translating an error code into the C++ exception.
   
  +
== Calling C Procedures ==
  +
  +
=== How do I call a C procedure from a Haskell program? ===
  +
  +
First, you'll want to keep open
  +
the [http://www.haskell.org/ghc/docs/latest/html/users_guide/ffi.html GHC user manual section on foreign function calling], and the
  +
[http://www.cse.unsw.edu.au/~chak/haskell/ffi/ Haskell FFI addendum].
  +
  +
Now, let's assume you got this c-program ffi.c which writes THE answer to a file:
  +
  +
<pre>
  +
#include <stdlib.h>
  +
#include <stdio.h>
  +
  +
write_answer(char *userfilename)
  +
{
  +
FILE *userfile;
  +
userfile=fopen(userfilename,"w");
  +
fprintf(userfile,"42");
  +
fclose(userfile);
  +
}
  +
</pre>
  +
You also need a header file ffi.h.
  +
<pre>
  +
void write_answer(char *userfilename)
  +
</pre>
  +
Next Step: Write the according Haskell program to include the function
  +
<tt>write_answer</tt> in your Haskell code:
  +
<haskell>
  +
{-# INCLUDE <ffi.h> #-}
  +
{-# LANGUAGE ForeignFunctionInterface #-}
  +
module Main where
  +
  +
import Foreign
  +
import Foreign.C.String
  +
  +
foreign import ccall "ffi.h write_answer" cwrite_answer :: CString -> IO ()
  +
  +
write_answer :: String -> IO ()
  +
write_answer s = do
  +
s' <- newCString s
  +
cwrite_answer s'
  +
  +
main = write_answer "ffi.dat"
  +
</haskell>
  +
  +
Now we get to compiling (assume that <tt>/tmp/ffi/</tt> is the current path).
  +
<pre>
  +
cc -fPIC -c ffi.c
  +
ar rc libffi.a ffi.o
  +
ghc -lffi -L/tmp/ffi --make Main
  +
</pre>
  +
And the resulting executable should write the file.
  +
  +
The <tt>-fPIC</tt> parameter to the c compiler is not strictly necessary.
  +
But the result will help us in the next step which is to dynamically link the library for use in GHCi.
  +
  +
== Compiling C Programs ==
  +
  +
=== How do I compile my C program to use in GHCi? ===
  +
  +
Suppose you got your c-program compiled (with <tt>-fPIC</tt> parameter) as described above. If you try to load your file <tt>Main.hs</tt> in GHCi you get an error similar to this:
  +
<pre>
  +
Loading object (dynamic) ffi ... failed.
  +
Dynamic linker error message was:
  +
libffi.so: cannot open shared object file: No such file or directory
  +
Whilst trying to load: (dynamic) ffi
  +
</pre>
  +
What you need is a shared library. To get it you compile once more:
  +
<pre>
  +
cc -shared -o libffi.so ffi.o
  +
</pre>
  +
And now it all works fine:
  +
<pre>
  +
$ ghci -lffi -L/tmp/ffi Main.hs
  +
GHCi, version 6.8.2: http://www.haskell.org/ghc/ :? for help
  +
Loading package base ... linking ... done.
  +
Loading object (dynamic) ffi ... done
  +
final link ... done
  +
Ok, modules loaded: Main.
  +
Prelude Main> write_answer "test"
  +
Prelude Main> :! cat test
  +
42
  +
Prelude Main>
  +
</pre>
   
 
---------------------------------------
 
---------------------------------------
Line 271: Line 433:
 
= Input/Output =
 
= Input/Output =
   
== If I print out a string using <tt>putStr</tt>, and then attempt to read some input using <tt>hGetLine</tt>, I don't see the output from the <tt>putStr</tt>. ==
+
== Strings ==
  +
  +
=== If I print out a string using <tt>putStr</tt>, and then attempt to read some input using <tt>hGetLine</tt>, I don't see the output from the <tt>putStr</tt>. ===
   
 
The <tt>stdout</tt> handle is line-buffered by default, which means that output sent to the handle is only flushed when a newline (<tt>\n</tt>) is output, the buffer is full, or <tt>hFlush</tt> is called on the <tt>Handle</tt>. The right way to make the text appear without sending a newline is to use <tt>hFlush</tt>:
 
The <tt>stdout</tt> handle is line-buffered by default, which means that output sent to the handle is only flushed when a newline (<tt>\n</tt>) is output, the buffer is full, or <tt>hFlush</tt> is called on the <tt>Handle</tt>. The right way to make the text appear without sending a newline is to use <tt>hFlush</tt>:
Line 286: Line 448:
 
You'll probably find that the behaviour differs when using GHCi: the hFlush isn't necessary to make the text appear. This is because in GHCi we turn off the buffering on stdout, because this is normally what you want in an interpreter: output appears as it is generated.
 
You'll probably find that the behaviour differs when using GHCi: the hFlush isn't necessary to make the text appear. This is because in GHCi we turn off the buffering on stdout, because this is normally what you want in an interpreter: output appears as it is generated.
   
== If I explicitly set the buffering on a Handle to <tt>NoBuffering</tt> I'm not able to enter EOF by typing "Ctrl-D". ==
+
=== If I use the above fix, but check for EOF with <tt>isEOF</tt> before prompting for user input, the above problem still happens (GHC 6.12.1) ===
  +
  +
== Buffering on Handles ==
  +
  +
=== If I explicitly set the buffering on a Handle to <tt>NoBuffering</tt> I'm not able to enter EOF by typing "Ctrl-D". ===
   
 
This is a consequence of Unixy terminal semantics. Unix does line buffering on terminals in the kernel as part of the terminal processing, unless you turn it off. However, the Ctrl-D processing is also part of the terminal processing which gets turned off when the kernel line buffering is disabled. So GHC tries its best to get NoBuffering semantics by turning off the kernel line buffering, but as a result you lose Ctrl-D. C'est la vie.
 
This is a consequence of Unixy terminal semantics. Unix does line buffering on terminals in the kernel as part of the terminal processing, unless you turn it off. However, the Ctrl-D processing is also part of the terminal processing which gets turned off when the kernel line buffering is disabled. So GHC tries its best to get NoBuffering semantics by turning off the kernel line buffering, but as a result you lose Ctrl-D. C'est la vie.
   
== When I open a FIFO (named pipe) and try to read from it, I get EOF immediately. ==
+
== FIFOs (Named Pipes) ==
  +
  +
=== When I open a FIFO (named pipe) and try to read from it, I get EOF immediately. ===
   
 
This is a consequence of the fact that GHC opens the FIFO in non-blocking mode. The behaviour varies from OS to OS: on Linux and Solaris you can wait for a writer by doing an explicit threadWaitRead on the file descriptor (gotten from <tt>Posix.handleToFd</tt>) before the first read, but this doesn't work on FreeBSD (although rumour has it that recent versions of FreeBSD changed the behaviour to match other OSs). A workaround for all systems is to open the FIFO for writing yourself, before (or at the same time as) opening it for reading.
 
This is a consequence of the fact that GHC opens the FIFO in non-blocking mode. The behaviour varies from OS to OS: on Linux and Solaris you can wait for a writer by doing an explicit threadWaitRead on the file descriptor (gotten from <tt>Posix.handleToFd</tt>) before the first read, but this doesn't work on FreeBSD (although rumour has it that recent versions of FreeBSD changed the behaviour to match other OSs). A workaround for all systems is to open the FIFO for writing yourself, before (or at the same time as) opening it for reading.
   
== When I foreign import a function that returns char or short, I get garbage back. ==
+
== Importing Functions Returning Char/Short ==
  +
  +
=== When I foreign import a function that returns char or short, I get garbage back. ===
   
 
This is a known bug in GHC versions prior to 5.02.2. GHC doesn't mask out the more significant bits of the result. It doesn't manifest with gcc 2.95, but apparently shows up with g++ and gcc 3.0.
 
This is a known bug in GHC versions prior to 5.02.2. GHC doesn't mask out the more significant bits of the result. It doesn't manifest with gcc 2.95, but apparently shows up with g++ and gcc 3.0.
   
 
---------------------------------------
 
---------------------------------------
= Optimization issues =
+
= Optimization =
  +
  +
== Garbage Collection ==
   
== My program spent too much time doing garbage collection ==
+
=== My program spent too much time doing garbage collection ===
   
 
Add the "+RTS -A10m" option to the command line when you run your
 
Add the "+RTS -A10m" option to the command line when you run your
Line 314: Line 476:
 
to force your program to use this setting on each run.
 
to force your program to use this setting on each run.
   
  +
== Subexpression Elimination ==
   
== Does GHC do common subexpression elimination? ==
+
=== Does GHC do common subexpression elimination? ===
   
 
In general, GHC does not do CSE.
 
In general, GHC does not do CSE.
Line 337: Line 500:
 
or <hask>where</hask>.
 
or <hask>where</hask>.
   
== When can I rely on full laziness? ==
+
== Laziness ==
  +
  +
=== When can I rely on full laziness? ===
   
 
Consider this program
 
Consider this program
Line 367: Line 530:
 
---------------------------------------
 
---------------------------------------
   
= Other frequently asked questions =
+
= Miscellaneous =
   
== Do I have to recompile all my code if I upgrade GHC? ==
+
== Upgrading GHC ==
  +
  +
=== Do I have to recompile all my code if I upgrade GHC? ===
   
 
Yes. There are two reasons for this:
 
Yes. There are two reasons for this:
Line 376: Line 539:
 
* We sometimes change the ABI (application binary interface) between versions of GHC. Code compiled with one version of GHC is not necessarily compatible with code compiled by a different version, even if you arrange to keep the same libraries.
 
* We sometimes change the ABI (application binary interface) between versions of GHC. Code compiled with one version of GHC is not necessarily compatible with code compiled by a different version, even if you arrange to keep the same libraries.
   
== Why doesn't GHC use shared libraries? ==
+
== Shared Libraries ==
  +
  +
=== Why doesn't GHC use shared libraries? ===
   
 
GHC does provide shared libraries, currently only on MacOS X. We are working on making shared libraries work on other platforms.
 
GHC does provide shared libraries, currently only on MacOS X. We are working on making shared libraries work on other platforms.
Line 382: Line 545:
 
However, GHC-compiled libraries are very tightly coupled, which means it's unlikely you'd be able to swap out a shared library for a newer version unless it was compiled with exactly the same compiler and set of libraries as the old version.
 
However, GHC-compiled libraries are very tightly coupled, which means it's unlikely you'd be able to swap out a shared library for a newer version unless it was compiled with exactly the same compiler and set of libraries as the old version.
   
== My program is failing with head [], or an array bounds error, or some other random error, and I have no idea how to find the bug. Can you help? ==
+
== Debugging ==
   
Compile your program with <tt>-prof -auto-all</tt> (make sure you have the profiling libraries installed), and run it with <tt>+RTS -xc -RTS</tt> to get a ´stack trace¡ at the point at which the exception was raised. See [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-options-debugging Section 4.14.4, ´RTS options for hackers, debuggers, and over-interested souls¡] for more details.
+
=== My program is failing with head [], or an array bounds error, or some other random error, and I have no idea how to find the bug. Can you help? ===
   
== How do I increase the heap size permanently for a given binary? ==
+
Try the [http://www.haskell.org/ghc/docs/latest/html/users_guide/ghci-debugger.html GHCi Debugger], in particular look at the section on "Debugging Exceptions".
   
See [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-hooks Section 4.14.5, ´´Hooks¡ to change RTS behaviour¡].
+
Alternatively, compile your program with <tt>-prof -auto-all</tt> (make sure you have the profiling libraries installed), and run it with <tt>+RTS -xc -RTS</tt> to get a ´stack trace at the point at which the exception was raised. See [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-options-debugging Section 4.14.4, ´RTS options for hackers, debuggers, and over-interested souls] for more details.
   
== I'm trying to compile my program for parallel execution with the -parallel, and GHC complains with an error like ´failed to load interface file for Prelude¡. ==
+
== Increasing Heap Size ==
  +
  +
=== How do I increase the heap size permanently for a given binary? ===
  +
  +
See [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-hooks Section 4.14.5, ´´Hooks to change RTS behaviour].
  +
  +
== Compiling for Parallel Execution ==
  +
  +
=== I'm trying to compile my program for parallel execution with the -parallel, and GHC complains with an error like 'failed to load interface file for Prelude'. ===
   
 
GHC doesn't ship with support for parallel execution; that support is provided separately by the [http://www.macs.hw.ac.uk/~dsg/gph/ GPH] project.
 
GHC doesn't ship with support for parallel execution; that support is provided separately by the [http://www.macs.hw.ac.uk/~dsg/gph/ GPH] project.
   
== When is it safe to use [[unsafe functions]] such as <hask>unsafePerformIO</hask>? ==
+
== Using Unsafe Functions ==
  +
  +
=== When is it safe to use [[unsafe functions]] such as <hask>unsafePerformIO</hask>? ===
   
 
We'll give two answers to this question, each of which may be helpful. These criteria are not rigorous in any real sense (you'd need a formal semantics for Haskell in order to give a proper answer to this question), but should give you a feel for the kind of things you can and cannot do with unsafePerformIO.
 
We'll give two answers to this question, each of which may be helpful. These criteria are not rigorous in any real sense (you'd need a formal semantics for Haskell in order to give a proper answer to this question), but should give you a feel for the kind of things you can and cannot do with unsafePerformIO.
Line 403: Line 566:
 
For more information, see [http://www.haskell.org/pipermail/glasgow-haskell-users/2002-July/003681.html this thread].
 
For more information, see [http://www.haskell.org/pipermail/glasgow-haskell-users/2002-July/003681.html this thread].
   
== I can't get finalizers to work properly. My program sometimes just prints <tt><<loop>></tt>. ==
+
== Using Finalizers ==
  +
  +
=== I can't get finalizers to work properly. My program sometimes just prints <tt><<loop>></tt>. ===
   
 
Chances are that your program is trying to write a message to stdout or stderr in the finalizer. Handles have finalizers themselves, and since finalizers don't keep other finalized values alive, the stdout and stderr Handles may be finalized before your finalizer runs. If this happens, your finalizer will block on the handle, and probably end up receiving a NonTermination exception (which is printed as <tt><<loop>></tt>).
 
Chances are that your program is trying to write a message to stdout or stderr in the finalizer. Handles have finalizers themselves, and since finalizers don't keep other finalized values alive, the stdout and stderr Handles may be finalized before your finalizer runs. If this happens, your finalizer will block on the handle, and probably end up receiving a NonTermination exception (which is printed as <tt><<loop>></tt>).
   
== Does GHC implement any kind of extensible records? ==
+
== Extensible Records ==
  +
  +
=== Does GHC implement any kind of extensible records? ===
   
 
No, extensible records are not implemented in GHC. [http://www.haskell.org/hugs/ Hugs] implements TRex, one extensible record variant. The problem is that the record design space is large, and seems to lack local optima. And all reasonable variants break backward compatibility. As a result, nothing much happens.
 
No, extensible records are not implemented in GHC. [http://www.haskell.org/hugs/ Hugs] implements TRex, one extensible record variant. The problem is that the record design space is large, and seems to lack local optima. And all reasonable variants break backward compatibility. As a result, nothing much happens.
  +
  +
== Using Extra GCC/Linker Options ==
  +
  +
=== How can I make GHC always use some extra gcc or linker option? ===
  +
  +
If you want to *always* use an extra option then you can edit the package configuration for the 'rts' or 'base' package since these packages are used by every program that you compile with GHC. You might want to do this if you had installed something that ghc needs but into a non-standard directory, thus requiring special compilation or linking options.
  +
  +
All you need to do is to dump out the configuration into a human readable form, edit it and re-register the modified package configuration. The exact commands to do that are below, but first here are the fields in the file that you might want to modify:
  +
  +
; include-dirs: directories to search for .h files
  +
; library-dirs: directories to search for libraries
  +
; extra-libraries: extra C libs to link with
  +
; cc-options: extra flags to pass to gcc when compiling C code or assembly
  +
; ld-options: extra flags to pass to '''gcc''' when linking
  +
  +
to edit the rts package (or base) confiuration just do:
  +
# <tt>ghc-pkg describe rts > rts.package.conf</tt>
  +
# edit <tt>rts.package.conf</tt> with your favourite text editor
  +
# <tt>ghc-pkg update rts.package.conf</tt>
  +
  +
On Unix systems and Windows, some options can also be set with environment variables such as LIBRARY_PATH and C_INCLUDE_PATH.

Latest revision as of 10:07, 14 February 2014

Please feel free to add stuff here.

This page is rather long. We've started to add some sub-headings, but would welcome your help in making it better organised.

Contents

[edit] 1 GHC (Platform-specific Issues)

[edit] 1.1 Porting GHC

[edit] 1.1.1 How do I port GHC to platform X?

There are two distinct possibilities: either

  • The hardware architecture for your system is already supported by GHC, but you're running an OS that isn't supported (or perhaps has been supported in the past, but currently isn't). This is the easiest type of porting job, but it still requires some careful bootstrapping.
  • Your system's hardware architecture isn't supported by GHC. This will be a more difficult port (though by comparison perhaps not as difficult as porting gcc).

Both ways require you to bootstrap from intermediate HC files: these are the stylised C files generated by GHC when it compiles Haskell source. Basically the idea is to take the HC files for GHC itself to the target machine and compile them with gcc to get a working GHC, and go from there.

The Building Guide has all the details on how to bootstrap GHC on a new platform.


[edit] 1.2 Linux-related

[edit] 1.2.1 Missing libreadline.so.x Errors

[edit] 1.2.1.1 I Can't run GHCi on Linux, because it complains about a missing libreadline.so.3.

The "correct" fix for this problem is to install the correct package for the particular flavour of Linux on your machine. If this isn't an option, however, there is a hack that might work: make a symbolic link from libreadline.so.4 to libreadline.so.3 in /usr/lib. We tried this on a SuSE 7.1 box and it seemed to work, but YMMV.

[edit] 1.2.2 Linking Errors

[edit] 1.2.2.1 Linking a program causes the following error on Linux: /usr/bin/ld: cannot open -lgmp: No such file or directory

The problem is that your system doesn't have the GMP library installed. If this is a RedHat distribution, install the RedHat-supplied gmp-devel package, and the gmp package if you don't already have it. There have been reports that installing the RedHat packages also works for SuSE (SuSE doesn't supply a shared gmp library).

[edit] 1.2.3 SELinux-related

[edit] 1.2.3.1 Memory Allocation Errors

If you have SELinux enabled on your system, then GHC may fail with a memory allocation error:

 ghc-6.4.1: internal error: mallocBytesRWX: failed to protect 0x0x1660730

or maybe

 ghc: internal error: getMBlock: mmap: Permission denied 

The reason for this is that SELinux prevents allocation of writeable/executable memory regions, which GHC needs in order to implement certain parts of the FFI that require dynamic code generation. (See this bug report).

In GHC 6.4.2 we improved the situation somewhat, but not completely.

Workarounds:

  • Set allow_execmem to 0, with the setsebool command.
  • do this on a per-program basis, for GHC and GHC-compiled programs. Apparently this is done by:
      /usr/bin/chcon -t unconfined_execmem_exec_t /path/to/binary/prog

[edit] 1.3 Solaris-related

[edit] 1.3.1 Link Errors

[edit] 1.3.1.1 Solaris users may sometimes get link errors due to libraries needed by GNU Readline.

We suggest you try linking in some combination of the termcap, curses and ncurses libraries, by giving -ltermcap, -lcurses and -lncurses respectively. If you encounter this problem, we would appreciate feedback on it, since we don't fully understand what's going on here. The build fails in readline.

It has been reported that if you have multiple versions of the readline library installed on Linux, then this may cause the build to fail. If you have multiple versions of readline, try uninstalling all except the most recent version.

[edit] 1.4 Windows-related

[edit] 1.4.1 Heapsize-related Crashes

[edit] 1.4.1.1 My program that uses a really large heap crashes on Windows.

For utterly horrible reasons, programs that use more than 128Mb of heap won't work when compiled dynamically on Windows (they should be fine statically compiled).

[edit] 1.4.2 Ctrl-C Not Working

When running GHC under a Cygwin shell on Windows, Ctrl-C sometimes doesn't work. A workaround is to use Ctrl-Break instead. Another workaround is to use the rlwrap program (cygwin package available) to invoke ghci : In addition to proper Ctrl-C, you also get emacs (or vi) key bindings and command history across sessions.

[edit] 1.4.3 Linking with Visual Studio C++ Code

[edit] 1.4.3.1 How do I link Haskell with C++ code compiled by Visual Studio?

[edit] 1.4.3.1.1 Prerequisites

It is assumed that the reader is familiar with the Haskell Foreign function interface (FFI), and is able to compile Haskell programs with GHC and C++ programs with Visual Studio.

[edit] 1.4.3.1.2 Background

GHC has two modes of code generation. It either compiles Haskell straight into object code (native mode), or translates Haskell into intermediate C code, and uses a C compiler as backend.

The Windows distribution of GHC comes bundled with the GCC compiler, which is used as backend. That's why linking Haskell with Visual C++ is no different from linking GCC-generated code with the code generated by Visual C++.

One cannot statically link together object files produced by those two compilers, but they can be linked dynamically: an executable produced by Visual C++ can invoke a DLL produced by GCC, and vice versa. Likewise, we can link Haskell with Visual C++ in one of these ways.

Note: when Haskell becomes able to use Visual C++ as a backend (see [1]), we would not need to go via a DLL anymore. Instead, we would simply list all source files (Haskell and C++) on the command line of GHC.

[edit] 1.4.3.1.3 Invoking a Haskell DLL
[edit] 1.4.3.1.3.1 From a C++ executable
  1. Make a Haskell DLL as explained in [2]
  2. Make a module definition file, such as
    LIBRARY Adder
    EXPORTS
        adder
  3. Create an import library using Visual Studio's lib.exe:
    lib /DEF:adder.def /OUT:adder.lib
  4. Link the C++ program against the import library.
[edit] 1.4.3.1.3.2 From a Haskell executable
  1. Make a DLL project in Visual Studio. It will create a .vcproj and .sln files for you. Add your C++ source files to this project.
  2. Create a .def file for your DLL. It might look like
    LIBRARY MyDLL
    EXPORTS
        function1
        function2
    where function1 and function2 are the names of the C++ functions that you want to invoke from Haskell (there can be more of them, of course), MyDLL is the name of your DLL.
  3. Create an import library that can be used by ghc:
    dlltool -d MyDLL.def -l libMyDLL.a
  4. Link your Haskell project, adding the library:
    ghc --make main.hs -optl-lMyDLL -optl-L.
    mind the dot at the end of the command line!
    (-optl switch passes its argument as an option to the linker).

[edit] 1.4.4 GHCi Hanging Issues

[edit] 1.4.4.1 GHCi hangs after "Loading package base ... linking ... done."

On a small number of systems GHCi will fail to start, hanging after loading the base package. The "Prelude>" prompt is never reached.

This is believed to be due to a bug in Windows thought to affect tablet PCs, although the details are not fully understood.

A workaround is to open a command prompt, enter "chcp 28591" - if this hangs hit Ctrl-C - and then run "ghci". Some users may find this hotfix useful.

[edit] 1.4.5 A console window opens when my application is supposed to be GUI only

Windows has several different "subsystems", the default subsystem which the mingw linker uses is console, so that stdout/stderr can be printed on screen and stdin be read from the console window.

This can be solved by giving the option -optl-mwindows with the compile command:

 ghc --make -optl-mwindows MyProgramWithGUI.lhs

With this option, the option -mwindows is passed to the linker.

Caveat: attempting to read from stdin with -mwindows set may cause a runtime error, any output on stdout/stderr will be lost.

[edit] 1.5 .NET/JVM Availability

[edit] 1.5.1 Why isn't GHC available for .NET or on the JVM?

It would make a lot of sense to give GHC a .NET or JVM back end, and it's a question that comes up regularly. The reason that we haven't done it here, at GHC HQ, is because it's a more substantial undertaking than might at first appear (see below). Furthermore, it'd permanently add a complete new back-end platform for us to maintain. Given our rather limited development effort, we have so far not bitten the bullet, and we have no immediate plans to do so.

It would be a good, well-defined project for someone else to tackle, and we would love to see it done. There is some good groundwork already done:

  • Sigbjorn Finne did a simple interop implementation (the hs-dotnet package) that allows a Haskell program to be compiled to native code (as now) but to call .NET programs via a variant of the FFI. I don't think this work is in active use, and I'd be surprised if it worked out of the box, but it could probably be revived with modest effort
  • Andre Santos and his colleagues at UFPE in Brazil are working on a .NET back end, that generates CLR IL, though I don't know where they are up to.
  • Nigel Perry and Oliver Hunt have a Haskell.NET prototype that works using GHC to compile to Core, and then compiling Core to NET. I'm not sure what stage it is at.
  • GHC.Net would be extra attractive if there was a Visual Studio integration for GHC. Substantial progress on this has been made in 2004 by Simon Marlow, Krasimir Angelov, and Andre Santos and colleagues.
  • Brian Alliet created a patch for GHC called LambdaVM that compiles programs into JVM bytecode. [3]
  • Not GHC but UHC: the Jazy backend of UHC generates Java class files to allow Haskell programs to run on the Java Virtual Machine (JVM). Jazy is not fully functional yet.


There may be others that I don't know of. If anyone wants to join in this effort, do contact the above folk. And please keep us informed!

Here's a summary of why it's a non-trivial thing to do (using .NET language, but it mostly applies to the JVM too):

  • The first thing is to generate native CLR Intermediate Language (IL). That's not really hard. Requires thinking about representations for thunks and functions, and it may not be particularly efficient, but it can surely be done.
An open question is about whether to generate verifiable IL or not. The trouble here is that Haskell's type system is more expressive than the CLR's in some ways, notably the use of higher-kinded type variables. So, to generate verifiable IL one is bound to need some run-time casts, and it's not clear how to minimise these.

At first blush this is all you need do. But it isn't!

  • Next, you need to think about how to inter-operate with .NET libraries. You don't really want to write "foreign import..." for each and every import. You'd like GHC to read the CLR meta-data directly. But there are lots of tricky issues here; see the paper that Mark Shields and I wrote about "Object-oriented style overloading for Haskell".
  • A closely-related question is this: how to make the type systems of Java/.NET and Haskell "line up"? For example, when importing a Java procedure, what is the Haskell type that corresponds to its .NET/JVM type? How do you sub-class a .NET class in Haskell? For example Object-Oriented Style Overloading for Haskell gives one "take" on the subject, but there are plenty of other possibilities.
  • Now you need to figure out how to implement GHC's primitive operations:
Not all of these are necessary, of course, but many are used in the libraries. The CLR supports many of them (e.g. concurrency) but with a very different cost model.
  • Last, you have to figure out what to do for the libraries. GHC has a pretty large library, and you either have to implement the primops on which the library is based (see previous point), or re-implement it. For example, GHC's implementation of I/O uses mutable state, concurrency, and more besides. For each module, you need to decide either to re-implement it using .NET primitives, or to implement the stuff the module is based on.

These challenges are mostly broad rather than deep. But to get a production quality implementation that runs a substantial majority of Haskell programs "out of the box" requires a decent stab at all of them.

[edit] 1.6 Mac OS X-related

[edit] 1.6.1 Linking with GHC

[edit] 1.6.1.1 Linking with ghc produces ld: Undefined symbols: _sprintf$LDBLStub ...

This happens on a PowerPC Mac OS X 10.4 if gcc-3.3 is the default compiler and you try to compile with a ghc that has been built with gcc-4.0. For example:

 $ cat t2.hs 
 module Main where
   main = putStr ("t2: Hello trac 1066 2007-Feb-17 19.48\n")
 $ gcc --version
 gcc (GCC) 3.3 20030304 (Apple Computer, Inc. build 1819)
 ...
 $ ghc --make t2.hs
 [1 of 1] Compiling Main             ( t2.hs, t2.o )
 Linking t2 ...
 ld: Undefined symbols:
 _sprintf$LDBLStub
 _fprintf$LDBLStub
 _vfprintf$LDBLStub
 _sscanf$LDBLStub
 $ 

To correct this, set the default compiler to gcc-4.0 (sudo gcc_select 4.0) or include linking options -lHSrts -lSystemStubs in that order on the ghc command:

 $ ghc --make t2.hs -lHSrts -lSystemStubs
 [1 of 1] Skipping  Main             ( t2.hs, t2.o )
 Linking t2 ...
 $ 

The command

 for l in <ghc installation directory>/lib/ghc-<ghc version>/*.a; do nm $l 2>&1 | if grep LDBLStub 1>/dev/null; then echo $l; fi; done

prints the list of libraries that may be needed instead of or in addition to -lHSrts before -lSystemStubs on the ghc command. For example:

 $ for l in /Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/*.a; do nm $l 2>&1 | if grep LDBLStub 1>/dev/null; then echo $l; fi; done
 /Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSX11_cbits.a
 /Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts.a
 /Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_debug.a
 /Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_p.a
 /Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_thr.a
 /Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_thr_debug.a
 /Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_thr_p.a
 $ 

[4] has additional details.

[edit] 1.6.2 Linking with C++

[edit] 1.6.2.1 Linking with a C++ library gives: Undefined symbols: __Unwind_Resume

You need to pass the -fexceptions to the linker. Use -optl -fexceptions.


[edit] 2 Running GHC

[edit] 2.1 Filenames Containing '+'

[edit] 2.1.1 GHC doesn't like filenames containing '+'.

Indeed not. You could change + to p or plus.

[edit] 2.2 Linking

[edit] 2.2.1 Why does linking take so long?

Linking a small program should take no more than a few seconds. Larger programs can take longer, but even linking GHC itself only takes 3-4 seconds on our development machines.

Long link times have been attributed to using Sun's linker on Solaris, as compared to GNU ld which appears to be much faster. So if you're on a Sun box, try switching to GNU ld. This article from the mailing list has more information.

One huge slowdown is also working on remote filesystem, e.g., nfs. Work on a local machine, preferably.

You may also speed up linking by enabling dynamic linking with the -dynamic option of GHC or --enable-executable-dynamic of Cabal.

[edit] 2.3 Missing Include Files

[edit] 2.3.1 Why do I get errors about missing include files when compiling with -O or -prof?

Certain options, such as -O, turn on via-C compilation, instead of using the native code generator. Include files named by -#include options or in foreign import declarations are only used in via-C compilation mode. See Section 8.2.2.1, ´Finding Header files for more details.

[edit] 2.4 Compiling for Profiling

[edit] 2.4.1 How do I compile my program for profiling without overwriting the object files and hi files I've already built?

You can select alternative suffixes for object files and interface files, so you can have several builds of the same code coexisting in the same directory. For example, to compile with profiling, you might do this:

    ghc --make -prof -o foo-prof -osuf p.o -hisuf p.hi Main

See Section 4.6.4, ´Redirecting the compilation output(s) for more details on the -osuf and -hisuf options.


[edit] 3 Syntax

[edit] 3.1 String Gaps

[edit] 3.1.1 I can't get string gaps to work

If you're also using CPP, beware of the known pitfall with string gaps mentioned in Section 4.10.3.1, CPP and string gaps.


[edit] 4 GHCi

[edit] 4.1 Error Messages

[edit] 4.1.1 Missing Symbols

[edit] 4.1.1.1 GHCi complains about missing symbols like CC_LIST when loading a previously compiled .o file.

This probably means the .o files in question were compiled for profiling (with -prof). Workaround: recompile them without profiling. We really ought to detect this situation and give a proper error message.

[edit] 4.1.2 Starting GHCi

[edit] 4.1.2.1 When I try to start ghci (probably one I compiled myself) it says ghc-5.02: not built for interactive use

To build a working ghci, you need to build GHC 5.02 with itself; the above message appears if you build it with 4.08.X, for example. It'll still work fine for batch-mode compilation, though. Note that you really must build with exactly the same version of the compiler. Building 5.02 with 5.00.2, for example, may or may not give a working interactive system; it probably won't, and certainly isn't supported. Note also that you can build 5.02 with any older compiler, back to 4.08.1, if you don't want a working interactive system; that's OK, and supported.

[edit] 4.1.3 Duplicate Definitions

[edit] 4.1.3.1 I get an error message from GHCi about a "duplicate definition for symbol __module_registered"

An error message like this:

    GHCi runtime linker: fatal error: I found a duplicate definition for symbol
           __module_registered
        whilst processing object file
           /usr/local/lib/ghc-6.2/HSfgl.o

probably indicates that when building a library for GHCi (HSfgl.o in the above example), you should use the -x option to ld.

[edit] 4.2 REPL Workarounds

[edit] 4.2.1 Why doesn't "x=1" work at the ghci prompt?

Type

    let x = 1

instead.

From IRC: "But in general, it's tricky to define function interactively. You can do simple stuff easily enough: "let f x = x * x" or whatever; but for anything other than a simple one-liner, I usually stick it into a file and then load it with ghci.


[edit] 5 The Foreign Function Interface

[edit] 5.1 Blocking

[edit] 5.1.1 When do other Haskell threads get blocked by an FFI call?

safe unsafe
-threaded NO YES
no -threaded YES YES

The -threaded flag (given when linking; see the manual) allows other Haskell threads to run concurrently with a thread making an FFI call. This nice behaviour does not happen for foreign calls marked as `unsafe` (see the FFI Addendum).

There used to be another modifier, threadsafe, which is now deprecated. Use `safe` instead.

[edit] 5.2 Using Floats

[edit] 5.2.1 When I use a foreign function that takes or returns a float, it gives the wrong answer, or crashes.

You should use the -#include option to bring the correct prototype into scope (see Section 4.10.5, ´Options affecting the C compiler (if applicable)).

[edit] 5.3 Propogating Run-time Errors as Exceptions

[edit] 5.3.1 How can I propagate a Haskell run-time error (e.g. pattern match failure) as an exception to a foreign caller of the Haskell function.

If a runtime error occurs inside a DLL compiled by ghc (like "irrefutable pattern match failed" or exceptions caused by error), the application that called the DLL function dies. This is ok for development but unacceptable when it happens with a user sitting in front of the display. So the question is: Is there any way to catch and process runtime errors? I am looking for some way to map those errors to exceptions on the C++ side that can be caught if required. It would be ok to kill the Haskell runtime system and unload the DLL if necessary.

Answer: The FFI doesn't provide any way to propagate exceptions from Haskell to the caller of a foreign export, because there's no standard way to do this. It is your responsibility to catch the exception in Haskell and return an appropriate error code to the caller. To raise a C++ exception, you would probably need another C++ wrapper around each foreign export, translating an error code into the C++ exception.

[edit] 5.4 Calling C Procedures

[edit] 5.4.1 How do I call a C procedure from a Haskell program?

First, you'll want to keep open the GHC user manual section on foreign function calling, and the Haskell FFI addendum.

Now, let's assume you got this c-program ffi.c which writes THE answer to a file:

#include <stdlib.h>
#include <stdio.h>

write_answer(char *userfilename)
{
  FILE *userfile;
  userfile=fopen(userfilename,"w");
  fprintf(userfile,"42");
  fclose(userfile);
}

You also need a header file ffi.h.

void write_answer(char *userfilename)

Next Step: Write the according Haskell program to include the function write_answer in your Haskell code:

{-# INCLUDE <ffi.h> #-}
{-# LANGUAGE ForeignFunctionInterface #-}
module Main where
 
import Foreign
import Foreign.C.String	
 
foreign import ccall "ffi.h write_answer" cwrite_answer :: CString -> IO ()
 
write_answer :: String -> IO ()
write_answer s = do
  s' <- newCString s
  cwrite_answer s'
 
main = write_answer "ffi.dat"

Now we get to compiling (assume that /tmp/ffi/ is the current path).

cc -fPIC -c ffi.c
ar rc libffi.a ffi.o
ghc -lffi -L/tmp/ffi --make Main

And the resulting executable should write the file.

The -fPIC parameter to the c compiler is not strictly necessary. But the result will help us in the next step which is to dynamically link the library for use in GHCi.

[edit] 5.5 Compiling C Programs

[edit] 5.5.1 How do I compile my C program to use in GHCi?

Suppose you got your c-program compiled (with -fPIC parameter) as described above. If you try to load your file Main.hs in GHCi you get an error similar to this:

Loading object (dynamic) ffi ... failed.
Dynamic linker error message was:
   libffi.so: cannot open shared object file: No such file or directory
Whilst trying to load:  (dynamic) ffi

What you need is a shared library. To get it you compile once more:

cc -shared -o libffi.so ffi.o

And now it all works fine:

$ ghci -lffi -L/tmp/ffi Main.hs
GHCi, version 6.8.2: http://www.haskell.org/ghc/  :? for help
Loading package base ... linking ... done.
Loading object (dynamic) ffi ... done
final link ... done
Ok, modules loaded: Main.
Prelude Main> write_answer "test"
Prelude Main> :! cat test
42
Prelude Main>              

[edit] 6 Input/Output

[edit] 6.1 Strings

[edit] 6.1.1 If I print out a string using putStr, and then attempt to read some input using hGetLine, I don't see the output from the putStr.

The stdout handle is line-buffered by default, which means that output sent to the handle is only flushed when a newline (\n) is output, the buffer is full, or hFlush is called on the Handle. The right way to make the text appear without sending a newline is to use hFlush:

      import System.IO
      main = do
        putStr "how are you today? "
        hFlush stdout
        input <- hGetLine stdin
        process input

You'll probably find that the behaviour differs when using GHCi: the hFlush isn't necessary to make the text appear. This is because in GHCi we turn off the buffering on stdout, because this is normally what you want in an interpreter: output appears as it is generated.

[edit] 6.1.2 If I use the above fix, but check for EOF with isEOF before prompting for user input, the above problem still happens (GHC 6.12.1)

[edit] 6.2 Buffering on Handles

[edit] 6.2.1 If I explicitly set the buffering on a Handle to NoBuffering I'm not able to enter EOF by typing "Ctrl-D".

This is a consequence of Unixy terminal semantics. Unix does line buffering on terminals in the kernel as part of the terminal processing, unless you turn it off. However, the Ctrl-D processing is also part of the terminal processing which gets turned off when the kernel line buffering is disabled. So GHC tries its best to get NoBuffering semantics by turning off the kernel line buffering, but as a result you lose Ctrl-D. C'est la vie.

[edit] 6.3 FIFOs (Named Pipes)

[edit] 6.3.1 When I open a FIFO (named pipe) and try to read from it, I get EOF immediately.

This is a consequence of the fact that GHC opens the FIFO in non-blocking mode. The behaviour varies from OS to OS: on Linux and Solaris you can wait for a writer by doing an explicit threadWaitRead on the file descriptor (gotten from Posix.handleToFd) before the first read, but this doesn't work on FreeBSD (although rumour has it that recent versions of FreeBSD changed the behaviour to match other OSs). A workaround for all systems is to open the FIFO for writing yourself, before (or at the same time as) opening it for reading.

[edit] 6.4 Importing Functions Returning Char/Short

[edit] 6.4.1 When I foreign import a function that returns char or short, I get garbage back.

This is a known bug in GHC versions prior to 5.02.2. GHC doesn't mask out the more significant bits of the result. It doesn't manifest with gcc 2.95, but apparently shows up with g++ and gcc 3.0.


[edit] 7 Optimization

[edit] 7.1 Garbage Collection

[edit] 7.1.1 My program spent too much time doing garbage collection

Add the "+RTS -A10m" option to the command line when you run your program. This sets the allocation area size used by the garbage collector to 10M, which should sufficiently decrease GC times (the default is 256K; see the section "Running a compiled program" in the users' guide). You can also add to your program C module containing statement

char *ghc_rts_opts = "-A10m";

to force your program to use this setting on each run.

[edit] 7.2 Subexpression Elimination

[edit] 7.2.1 Does GHC do common subexpression elimination?

In general, GHC does not do CSE. It'd be a relatively easy pass for someone to add, but it can cause space leaks. And it can replace two strictly-evaluated calls with one lazy thunk:

    let { x = case e of ...;  y = case e of ... } in ...
  ==>
    let { v = e; x = case v of ...; y = case v of ... } in ...
Now
v
is allocated as a thunk. (Of course, that might be well worth it if
e
is an expensive expression.)

Instead GHC does "opportunistic CSE". If you have

    let x = e in .... let y = e in ....

then it'll discard the duplicate binding. This can still cause space leaks but it guarantees never to create a new thunk, and it turns out to be very useful in practice.

Bottom line: if you care about sharing, do it yourself using
let
or
where
.

[edit] 7.3 Laziness

[edit] 7.3.1 When can I rely on full laziness?

Consider this program

  f x y = let r = expensive x 
          in r+y
  g vs = map (f 2) vs

Since r depends only on x, you might hope that (expensive 2) is computed just once. And that is indeed what will happen if you write

  f_opt x = let r = expensive x 
            in \y -> r+y
  g_opt vs = map (f_opt 2) vs

It's easy enough for a compiler to transform f into f_opt. (This is called the "full laziness" transformation.) BUT in the cases when f is fully-applied, f_opt is *less* efficient than f; consider

	h ys zs = zipWith f_opt ys zs

Reason: it's much less efficient to have separate lambdas \x-> let ... in \y -> e than one compound lambda \xy -> e.

So the best way to transform f depends on how it is used. When it's used locally and just once, GHC inlines it at the call site and all is good. But when it's exported or called many times, GHC's full laziness transformation uses the following rule: never "float" a let between two lambdas. So it won't transform f into f_opt.

On the other hand, if you write f_opt, GHC will keep it that way. Furthermore, if a sub-expression can be floated right out of a complete lambda group, GHC will float it out. For example

  f x vs = map (\y -> y + expensive x) vs

Here, the (expensive x) can be floated out of the \x->... lambda without separating two lambdas, and the full laziness transfom will do just that.


[edit] 8 Miscellaneous

[edit] 8.1 Upgrading GHC

[edit] 8.1.1 Do I have to recompile all my code if I upgrade GHC?

Yes. There are two reasons for this:

  • GHC does a lot of cross-module optimisation, so compiled code will include parts of the libraries it was compiled against (including the Prelude), so will be deeply tied to the actual version of those libraries it was compiled against. When you upgrade GHC, the libraries may change; even if the external interface of the libraries doesn't change, sometimes internal details may change because GHC optimised the code in the library differently.
  • We sometimes change the ABI (application binary interface) between versions of GHC. Code compiled with one version of GHC is not necessarily compatible with code compiled by a different version, even if you arrange to keep the same libraries.

[edit] 8.2 Shared Libraries

[edit] 8.2.1 Why doesn't GHC use shared libraries?

GHC does provide shared libraries, currently only on MacOS X. We are working on making shared libraries work on other platforms.

However, GHC-compiled libraries are very tightly coupled, which means it's unlikely you'd be able to swap out a shared library for a newer version unless it was compiled with exactly the same compiler and set of libraries as the old version.

[edit] 8.3 Debugging

[edit] 8.3.1 My program is failing with head [], or an array bounds error, or some other random error, and I have no idea how to find the bug. Can you help?

Try the GHCi Debugger, in particular look at the section on "Debugging Exceptions".

Alternatively, compile your program with -prof -auto-all (make sure you have the profiling libraries installed), and run it with +RTS -xc -RTS to get a ´stack trace at the point at which the exception was raised. See Section 4.14.4, ´RTS options for hackers, debuggers, and over-interested souls for more details.

[edit] 8.4 Increasing Heap Size

[edit] 8.4.1 How do I increase the heap size permanently for a given binary?

See Section 4.14.5, ´´Hooks to change RTS behaviour.

[edit] 8.5 Compiling for Parallel Execution

[edit] 8.5.1 I'm trying to compile my program for parallel execution with the -parallel, and GHC complains with an error like 'failed to load interface file for Prelude'.

GHC doesn't ship with support for parallel execution; that support is provided separately by the GPH project.

[edit] 8.6 Using Unsafe Functions

[edit] 8.6.1 When is it safe to use unsafe functions such as
unsafePerformIO
?

We'll give two answers to this question, each of which may be helpful. These criteria are not rigorous in any real sense (you'd need a formal semantics for Haskell in order to give a proper answer to this question), but should give you a feel for the kind of things you can and cannot do with unsafePerformIO.

  • It is safe to implement a function or API using unsafePerformIO if you could imagine also implementing the same function or API in Haskell without using unsafePerformIO (forget about efficiency, just consider the semantics).
  • In pure Haskell, the value of a function depends only on the values of its arguments (and free variables, if it has any). If you can implement the function using unsafePerformIO and still retain this invariant, then you're probably using unsafePerformIO in a safe way. Note that you need only consider the observable values of the arguments and result.

For more information, see this thread.

[edit] 8.7 Using Finalizers

[edit] 8.7.1 I can't get finalizers to work properly. My program sometimes just prints <<loop>>.

Chances are that your program is trying to write a message to stdout or stderr in the finalizer. Handles have finalizers themselves, and since finalizers don't keep other finalized values alive, the stdout and stderr Handles may be finalized before your finalizer runs. If this happens, your finalizer will block on the handle, and probably end up receiving a NonTermination exception (which is printed as <<loop>>).

[edit] 8.8 Extensible Records

[edit] 8.8.1 Does GHC implement any kind of extensible records?

No, extensible records are not implemented in GHC. Hugs implements TRex, one extensible record variant. The problem is that the record design space is large, and seems to lack local optima. And all reasonable variants break backward compatibility. As a result, nothing much happens.

[edit] 8.9 Using Extra GCC/Linker Options

[edit] 8.9.1 How can I make GHC always use some extra gcc or linker option?

If you want to *always* use an extra option then you can edit the package configuration for the 'rts' or 'base' package since these packages are used by every program that you compile with GHC. You might want to do this if you had installed something that ghc needs but into a non-standard directory, thus requiring special compilation or linking options.

All you need to do is to dump out the configuration into a human readable form, edit it and re-register the modified package configuration. The exact commands to do that are below, but first here are the fields in the file that you might want to modify:

include-dirs
directories to search for .h files
library-dirs
directories to search for libraries
extra-libraries
extra C libs to link with
cc-options
extra flags to pass to gcc when compiling C code or assembly
ld-options
extra flags to pass to gcc when linking

to edit the rts package (or base) confiuration just do:

  1. ghc-pkg describe rts > rts.package.conf
  2. edit rts.package.conf with your favourite text editor
  3. ghc-pkg update rts.package.conf

On Unix systems and Windows, some options can also be set with environment variables such as LIBRARY_PATH and C_INCLUDE_PATH.