真实世界 Haskell,第 5 章,SimpleJSON 编译错误

bpa*_*rni 2 haskell ghc

根据另一个问题,Real World Haskell 的部分内容现已过时。我只阅读了第 5 章,但是我在将一个简单示例编译为可执行二进制文件时遇到了问题。

给出了两个模块:

module SimpleJSON
    (
      JValue(..)
    , getString
    , getInt
    , getDouble
    , getBool
    , getObject
    , getArray
    , isNull
    ) where

data JValue = JString String
            | JNumber Double
            | JBool   Bool
            | JNull
            | JObject [ (String, JValue) ]
            | JArray [ JValue ]
              deriving (Eq, Ord, Show)

getString :: JValue -> Maybe String
getString (JString s) = Just s
getString _           = Nothing

getInt (JNumber n)    = Just (truncate n)
getInt _              = Nothing

getDouble (JNumber n) = Just n
getDouble _           = Nothing

getBool (JBool b)     = Just b
getBool _             = Nothing

getObject (JObject o) = Just o
getObject _           = Nothing

getArray (JArray a)   = Just a
getArray _            = Nothing

isNull v              = v == JNull
Run Code Online (Sandbox Code Playgroud)

module Main () where

import SimpleJSON

main = print (JObject [ ("foo", JNumber 1), ("bar", JBool False ) ])
Run Code Online (Sandbox Code Playgroud)

使用说明首先编译 SimpleJSON 对象文件:

$ ghc -c SimpleJSON.hs
Run Code Online (Sandbox Code Playgroud)

然后链接可执行文件:

$ ghc -o simple Main.hs SimpleJSON.o
Run Code Online (Sandbox Code Playgroud)

这会导致错误,指出“main”未导出:

[2 of 2] Compiling Main             ( Main.hs, Main.o )

Main.hs:1:1:
    The main function `main' is not exported by module `Main'
Run Code Online (Sandbox Code Playgroud)

但是,如果我添加main到导出列表或省略空导出列表,我会在链接阶段看到许多多个定义错误:

Linking simple ...
SimpleJSON.o:(.data+0x0): multiple definition of `__stginit_SimpleJSON'
./SimpleJSON.o:(.data+0x0): first defined here
SimpleJSON.o:(.data+0x0): multiple definition of `SimpleJSON_getArray_closure'
./SimpleJSON.o:(.data+0x0): first defined here
....
(.text+0x2d40): multiple definition of `SimpleJSON_JObject_static_info'
./SimpleJSON.o:(.text+0x2d40): first defined here
SimpleJSON.o: In function `SimpleJSON_JArray_info':
(.text+0x2d80): multiple definition of `SimpleJSON_JArray_static_info'
./SimpleJSON.o:(.text+0x2d80): first defined here
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

假设此错误是由文本所呈现的过时代码或过时 ghc 接口造成的,那么编译此 SimpleJSON 示例的正确方法是什么?

Sib*_*ibi 5

这应该有效:

ghc -o simple Main.hs SimpleJSON.hs
Run Code Online (Sandbox Code Playgroud)

或者甚至这样的事情应该工作:

ghc -c SimpleJSON.hs
ghc -c Main.hs
ghc -o simple Main.o SimpleJSON.o
Run Code Online (Sandbox Code Playgroud)

或者正如@chi 指出的那样,你可以使用这个:

ghc --make SimpleJSON.hs Main.hs
Run Code Online (Sandbox Code Playgroud)