Saturday, September 25, 2010

GHCi and Cabal

Maybe I'm the only one who didn't already know this, but I'd like to describe how to use GHCi within a Cabal project under development.

Say I'm working on a library foobar:

~/foobar $ find -type f
./foobar.cabal
./Data/FooBar.hs
./Setup.hs
./LICENSE

I want to write a test program, which won't go in the Cabal distribution:

~/foobar $ cat > test.hs
import Data.FooBar
main = print fooBar
^D

~/foobar $ cabal configure && cabal build
Resolving dependencies...
Configuring foobar-0.1...
Preprocessing library foobar-0.1...
Building foobar-0.1...
Registering foobar-0.1...

~/foobar $ ghci test.hs
GHCi, version 6.12.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 2] Compiling Data.FooBar      ( Data/FooBar.hs, interpreted )
[2 of 2] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Data.FooBar, Main.

GHCi is loading Data.FooBar into the interpreter, but I wanted to test the compiled, optimized version that was just produced by Cabal. Let's try telling it about the dist/ directory:

~/foobar $ ghci test.hs -package-conf dist/package.conf.inplace
GHCi, version 6.12.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 2] Compiling Data.FooBar      ( Data/FooBar.hs, interpreted )
[2 of 2] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Data.FooBar, Main.

Still no good. Seems that the existence of the file Data/FooBar.hs overrides anything in the package database. Move to another directory:

~/foobar      $ mkdir test && cd test
~/foobar/test $ mv ../test.hs .
~/foobar/test $ ghci test.hs -package-conf ../dist/package.conf.inplace
GHCi, version 6.12.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main> fooBar
Loading package foobar-0.1 ... linking ... done.
"testing 123"

It works. :) For compiled code as well:

~/foobar/test $ ghc --make -O test.hs -package-conf ../dist/package.conf.inplace
[1 of 1] Compiling Main             ( test.hs, test.o )
Linking test ...
~/foobar/test $ ./test
"testing 123"

No comments:

Post a Comment