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。ライブラリを作成したいので、GHC に-cフラグを指定する必要があります。その後は必要ありません-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;
}

TestLib.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 に答える