虽然网上有几个教程展示了如何使用Haskell函数编译C程序,但每个教程都使用ghc编译它们的C代码。在“真实世界”中,将使用gcc编译C代码文件。如何将Haskell代码集成到C程序中?
我的目标是从Haskell代码创建.o文件,然后将它们链接到核心C程序。以下是一个基本的工作示例。
Fibonacci.hs:
{-# LANGUAGE ForeignFunctionInterface #-}
module Fibonacci where
import Foreign
import Foreign.C.Types
fibonacci :: Int -> Int
fibonacci n = fibs !! n
where fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
fibonacci_hs :: CInt -> CInt
fibonacci_hs = fromIntegral . fibonacci . fromIntegral
foreign export ccall fibonacci_hs :: CInt -> CInt
test.c的:
#include "Fibonacci_stub.h"
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
hs_init(&argc, &argv);
i = fibonacci_hs(42);
printf("Fibonacci: %d\n", i);
hs_exit();
return 0;
}
的Makefile:
all: test
test: Fibonacci.o test.o
gcc -shared Fibonacci.o test.o -o test
test.o: test.c
gcc -c -I/usr/lib/ghc/include test.c
Fibonacci.o: Fibonacci.hs
ghc -c -O Fibonacci.hs
clean:
rm *.o *.hi test *_stub.h
https://dl.dropboxusercontent.com/u/14826353/fibonacci.tgz
当运行make,第一:GHC编译器会根创建一个Fibonacci_stub.h和一个Fibonacci.o文件。其次:gcc编译器将从test.c文件生成test.o文件。最后,gcc编译器应该链接.o文件并生成可执行文件。
而是提供这样的错误:
的/ usr /斌/ LD:Fibonacci.o:针对未定义的符号`base_GHCziBase_plusInt_closure”重定位R_X86_64_PC32不能创建共享对象时使用;与-fPIC 的/ usr/bin中/ LD编译:最后一个环节失败:错误值
输出表示使用-fPIC,我试图把它在几个地方,但这些尝试都没有取得丰硕成果在消除错误。
- 我应该在Makefile中放置-fPIC?
- -fPIC建议有用吗? Makefile中存在明显的缺陷,它会阻止编译?
或者,由于OP似乎不需要共享对象,因此他可能会尝试从'gcc -shared Fibonacci.o test.o -o test'中删除'-shared'。 – Armali