Possible Duplicate:
How to compile Haskell to a static library?
有人在使用 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”库文件。
最佳答案
从 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;
}
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 在创建库时不要进行链接,只有在最终创建可执行文件时才进行链接。
关于haskell - GHC编译库未定义 "main",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10543426/