[Haskell-cafe] Building shared library to be called from C

Jack Hill jackhill at jackhill.us
Thu Apr 7 16:52:39 UTC 2016


I'm attempting to build a shared library that can be called from C. My end 
goal is to build a PAM module, but for now I'm working with toy programs 
so that I can get a feel for building how to build the library.

The Haskell part looks like this (in a file called hfact.hs)

   module Hfact where

   import Foreign
   import Foreign.C.Types

   foreign export ccall fact_hs :: CInt -> CInt

   fact :: Int -> Int
   fact x = product [1..x]

   fact_hs :: CInt -> CInt
   fact_hs = fromIntegral . fact . fromIntegral

I can compile this into a so (I think successfully) with "ghc --make -shared -dynamic -fPIC -o libhfact.so hfact.hs".

Now I would like to be able to call this from C. I have a C program (in a file called main.c) as follows:

   #include <stdio.h>
   #include "HsFFI.h"
   #include "hfact_stub.h"

   int main(int argc, char *argv[]) {
     int user, answer;

     scanf("%d", &user);
     hs_init(&argc, &argv);
     answer = fact_hs(user);
     printf("Result: %d\n", answer);

     return 0;

Unfortunately, I'm at a loss for how to build and link this against my so.

If I try "gcc main.c -lhfact", I get many undefined symbol errors like:

/nfshomes/j/jackhill/.stack/programs/x86_64-linux/ghc-7.10.3/lib/ghc-7.10.3/base_HQfYBxpPvuw8OunzQu6JGM/libHSbase- undefined reference to `__hscore_get_saved_termios'

If I try "ghc maint.c -lhfact" I get:

/tmp/ghc19146_0/ghc_4.o: In function `main':
ghc_3.c:(.text+0x0): multiple definition of `main'
maint.o:maint.c:(.text+0x0): first defined here
/tmp/ghc19146_0/ghc_4.o: In function `main':
ghc_3.c:(.text+0x61): undefined reference to `ZCMain_main_closure'
collect2: error: ld returned 1 exit status

How should I be calling Haskell from C?


More information about the Haskell-Cafe mailing list