[Haskell-beginners] Compiling shared (dll) library

Daniel Fischer daniel.is.fischer at googlemail.com
Mon Dec 5 13:14:20 CET 2011


On Monday 05 December 2011, 11:39:06, Alexander.Vladislav.Popov wrote:
> Hi, Haskellers.
> 
> I'm trying to compile following program (where Regex.Genex is a package
> what I need to produce all possible expresions by the given pattern and
> `adder' is just FFI sample):
> 
> -- genexlib.hs
> {-# LANGUAGE BangPatterns, ForeignFunctionInterface #-}
> 
> module GenexLib where
> 
> import Regex.Genex
> import System.IO
> import System.Environment
> 
> adder :: Int -> Int -> IO Int  -- gratuitous use of IO
> adder x y = return (x+y)
> foreign export stdcall adder :: Int -> Int -> IO Int
> -- genexlib.hs end
> 
> // start.c
> #include <Rts.h>
> 
> void HsStart()
> {
>    int argc = 1;
>    char* argv[] = {"ghcDll", NULL}; // argv must end with NULL
> 
>    // Initialize Haskell runtime
>    char** args = argv;
>    hs_init(&argc, &args);
> }
> 
> void HsEnd()
> {
>    hs_exit();
> }
> // start.c end
> 
> I'm using ghc
> 
> >ghc --version
> 
> The Glorious Glasgow Haskell Compilation System, version 7.0.2
> 
> compiling:
> >ghc -c genexlib.hs
> >ghc -c start.c
> >ghc -shared -o genexlib.dll genexlib.o genexlib_stub.o start.o

Why the separate compilation? Can't you compile them in one go?

> 
> genexlib.o:fake:(.text+0xd1): undefined reference to
> `__stginit_regexzmgenexzm0zi3zi2_RegexziGenex_'
> Creating library file: genexlib.dll.a
> collect2: ld returned 1 exit status
> 
> and get undefined reference.
> 
> But If I try to compile the executable from similar code:
> 

> >ghc --make genexlib.hs -O2

By the way, --make is the default mode from ghc-7.0 on, so you don't need 
it here.

> Where is my mistake? What am I doing wrong?
> In first case, when compiling shared dll, I tried to link libraries what
> I've found in `cabal' directory (like `libHSregex-genex-0.3.2.a') to
> work around errors but all in vain.

The fundamental thing is that in --make mode, GHC figures out the required 
Haskell dependencies itself. So it sees the import and looks in which 
package it's provided and links (if necessary) with that package.

But when you tell it to link a couple of .o files, it's not in --make mode, 
so apart from the specified files it links in only symbols from a few 
select packages (I think the wired-in packages), so then you have to tell 
it which other packages it needs to link in.

$ ghc -shared -package regex-genex -o genexlib.dll genexlib.o 
genexlib_stub.o start.o

should fix the undefined reference.




More information about the Beginners mailing list