Yotam Ohad
Yotam Ohad

Reputation: 322

Haskell, error while linking two files

I've started reading about haskell with the book "Real World Haskell" and I've come into a problem I can't figure out. I have two files. The first, SimpleJSON.hs, contains the following code:

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 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

I've used "ghc -c SimpleJSON.hs" to get the object file. Then in my Main.hs

module Main (main) where

import SimpleJSON

main = print (JObject [("foo", JNumber 1), ("bar", JBool False)])

I'm import the second file, but when I run "ghc -o simple Main.hs SimpleJSON.o" to get a .exe file I get the following error:

collect2.exe: error: ld returned 1 exit status
`gcc.exe' failed in phase `Linker'. (Exit code: 1)

Thanks for your help

Upvotes: 3

Views: 516

Answers (1)

Dave Compton
Dave Compton

Reputation: 1441

The compiler should recognize that Main depends on SimpleJSON by virtue of the import SimpleJSON statement. This means that when you compile Main.hs, SimpleJSON.hs will also be compiled and linked into the resulting executable.

By specifying SimpleJSON.o explicitly on the command line you are probably linking that file twice into the resulting executable, which causes the failure you see.

ghc -o simple Main.hs should be enough to get your program to link.

Upvotes: 1

Related Questions