How to compile Haskell to a static library?

后端 未结 2 874
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 05:25

Hey, I\'m learning Haskell and I\'m interested in using it to make static libraries for using in Python and probably C. After some googling I found out how to get GHC to out

相关标签:
2条回答
  • 2020-12-08 05:34

    The canonical way of is this:

    1. Export the functions (via FFI) to initialise RTS (runtime system) by the foreign program
    2. Export actual functions you would like to implement in Haskell

    The following sections of manual describe this: [1] [2]

    On the other way, you can try technique described in this blog post (which mine, by the way):

    http://mostlycode.wordpress.com/2010/01/03/shared-haskell-so-library-with-ghc-6-10-4-and-cabal/

    It boils down to creating a small C file which is called automatically right after a library is loaded. It should be linked together into the library.

    #define CAT(a,b) XCAT(a,b)
    #define XCAT(a,b) a ## b
    #define STR(a) XSTR(a)
    #define XSTR(a) #a
    
    #include
    
    extern void CAT (__stginit_, MODULE) (void);
    
    static void library_init (void) __attribute__ ((constructor));
    static void
    library_init (void)
    {
          /* This seems to be a no-op, but it makes the GHCRTS envvar work. */
          static char *argv[] = { STR (MODULE) ".so", 0 }, **argv_ = argv;
          static int argc = 1;
    
          hs_init (&argc, &argv_);
          hs_add_root (CAT (__stginit_, MODULE));
    }
    
    static void library_exit (void) __attribute__ ((destructor));
    static void
    library_exit (void)
    {
        hs_exit ();
    }
    

    Edit: Original blog post describing this technique is this: http://weblog.haskell.cz/pivnik/building-a-shared-library-in-haskell/

    0 讨论(0)
  • 2020-12-08 05:34

    This makes ghc compile statically (note that the pthread is before optl-static): ghc --make -static -optl-pthread -optl-static test.hs

    Edit: But the static compilation seems to be a bit risky. Most of the times there are some errors. And on my x64 fedora it doesn't work at all. The resulting binary is also quite large, 1.5M for main = putStrLn "hello world"

    0 讨论(0)
提交回复
热议问题