gpt4 book ai didi

c - C2HS 生成的 C 绑定(bind)中的链接器错误

转载 作者:太空狗 更新时间:2023-10-29 16:11:52 24 4
gpt4 key购买 nike

我构建并运行了以下最小示例(无外部依赖项) C->Haskell Compiler, version 0.25.2 Snowboundest, 31 Oct 2014
build platform is "x86_64-darwin" <1, True, True, 1>
;构建命令:

c2hs Structs.chs
ghci Structs.hs

但是链接器提示

During interactive linking, GHCi couldn't find the following symbol: get_foo

问:为什么会这样,我该如何解决?提前致谢

答:tl;dr:我没有将 .c 编译成 .o 目标代码,DUH!

代码如下:

Structs.chs

module Main where

import Foreign
import Foreign.C

#include "Structs.h"

{#pointer *foo as Foo#}

{#fun get_foo {`Int'} -> `Foo' return* #}

main :: IO ()
main = do
foo <- get_foo 3
a1 <- {#get struct foo->a#} foo
print a1

Structs.h

struct foo {
int a;
};

struct foo *get_foo(int n);

Structs.c

#include "Structs.h"

struct foo f;

struct foo *get_foo(int n)
{
f.a = n;
return &f;
}

Structs.hs

-- -- C2HS generated Hs file, edited for clarity
module Main where

import Foreign
import Foreign.C

type Foo = Ptr ()

get_foo :: Int -> IO Foo
get_foo p =
get_foo'_ (fromIntegral p)

main :: IO ()
main = do
foo <- get_foo 3
a1 <- (\ptr -> peekByteOff ptr 0 :: IO CInt) foo
print a1

foreign import ccall safe "Structs.chs.h get_foo"
get_foo'_ :: CInt -> IO Foo

编辑:ghc --make Structs.hs给出相同的链接器错误:

$ ghc --make Structs.hs
Linking Structs1a ...
Undefined symbols for architecture x86_64:
"_get_foo", referenced from:
_c2MX_info in Structs.o
_c2Or_info in Structs.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

最佳答案

get_foo C 函数在 Structs.c 中定义,因此您需要让 GHC 可以使用它。这应该有效:

gcc -o Structs_c.o -c Structs.c
ghc --make Structs.hs Structs_c.o

对于 GHCi,我认为您可以说 ghci Structs.hs Structs_c.o。但是您肯定需要 C 目标文件!

关于c - C2HS 生成的 C 绑定(bind)中的链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29526738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com