Why i can't compile with GHC if code contain module definition?
I'am trying to compile a very small haskell code with ghc:
module Comma where
import System.IO
main = do
contents <- getContents
putStr (comma contents)
comma input =
let allLines = lines input
addcomma [x] = x
addcomma (x:xs) = x ++ "," ++ (addcomma xs)
result = addcomma allLines
in result
The command i'm using to compile is :
ghc --make Comma.hs
And i'm getting this answer:
[1 of 1] Compiling Comma ( Comma.hs, Comma.o )
No file is generated, and there is no warning or errors messages.
If i comment the "module Comma where" line from code it compiles correctly:
[1 of 1] Compiling Main ( Comma.hs, Comma.o ) Linking Comma ...
I don't understand what is happening. I'm using ghc 7,4,1 (Glasgow Haskell Compiler, Version 7.4.1, stage 2 booted by GHC version 7.4.1) and ubuntu linux.
I appreciate if anyone could tell why doesn't compile with the module definition
GHC compiles the function Main.main
to be the entry point of an executable. When you omit the module declaration, Module Main where
is implicitly inserted for you.
But when you explicitly name it something other than Main
ghc doesn't find an entry point.
My usual workflow is to use ghci
(or ghci + emacs) instead for these snippets which let's you bypass this issue entirely. Alternatively, you could compile with -main-is Comma
to explicitly tell ghc to use the Comma module.
No file is generated
Are you sure? I would expect that at least Comma.o
and Comma.hi
are generated. The former contains the compiled code ready to be linked into an executable, and the latter contains interface information that ghc uses to typecheck modules that import the module Comma
.
However, ghc will only link the compiled modules into an executable if there is a main function. By default, that means a function named main
in a module named Main
. If you don't put an explicit module name, the name Main
is assumed, and that's why your test works when you delete the module Comma where
line.
To compile and link the Comma.hs
file you can either use module Main where
instead of module Comma where
, or you can use the -main-is
flag to tell ghc that Comma.main
is to be the main function:
ghc --make -main-is Comma Comma.hs
Or:
ghc --make -main-is Comma.main Comma.hs
如果你在你的文件中有一个main
定义,并且你想将它编译成一个可执行文件,你只需要在module Main where
。