2

可能重复:
如何将 Haskell 编译为静态库?

有人在使用链接到另一个库的 GHC 编译库时遇到问题吗?

文件:

module TestLib where
foreign export ccall test_me :: IO (Int)
foreign import "mylib_do_test" doTest :: IO ( Int )
test_me = doTest

输出:

> ghc --version
The Glorious Glasgow Haskell Compilation System, version 7.0.4
> ghc TestLib.hs -o test -no-hs-main -L../libmylib -lmylib
Linking test ...
Undefined symbols:
  "_main", referenced from:
      start in crt1.10.6.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
>

我使用“ar -r -s ...”制作了“libmylib.a”库文件。

4

1 回答 1

3

从 ghc-7 开始,默认模式是--make. 你想创建一个库,所以你必须用-c标志告诉 GHC。你不需要那个-no-hs-main时候。

 ghc -c TestLib.hs -o test.o

作品。

一个例子:

clib.h:

int doTest(void);

clib.c:

#include "clib.h"

int doTest(void){
    return 42;
}

测试库.hs:

{-# LANGUAGE ForeignFunctionInterface #-}
module TestLib where

foreign export ccall test_me :: IO (Int)
foreign import ccall "clib.h" doTest :: IO ( Int )
test_me = doTest

libtest.c:

#include <stdio.h>
#include "TestLib_stub.h"

int main(int argc, char *argv[])
{
    hs_init(&argc, &argv);
    printf("%d\n", test_me());
    hs_exit();
    return 0;
}

编译和执行:

$ ghc -c -o clib.o clib.c
$ ar -r -s libclib.a clib.o
ar: creating libclib.a
$ ghc TestLib.hs -c -o tlib.o
$ ar -r -s libtlib.a tlib.o
ar: creating libtlib.a
$ ghc -o nltest libtest.c -no-hs-main -L. -ltlib -lclib
$ ./nltest
42

注意:这适用于 ghc >= 7.2; 对于 ghc-7.0.*,您还必须编译生成的TestLib_stub.c文件并使用TestLib_stub.o.

重要的一点是告诉 ghc在创建库时不要链接,只有在最终创建可执行文件时才链接。

于 2012-05-10T23:23:18.517 回答