Why can't I compile with GHC if the code contains a 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 use to compile:

ghc --make Comma.hs

And I get this answer:

[1 of 1] Compiling a comma (Comma.hs, Comma.o)

The file is not generated, and there are no error messages or errors.

If I comment on the β€œComma where module” from the code that it compiles correctly:

[1 of 1] Compiling Main (Comma.hs, Comma.o) Comma Linking ...

I do not understand what's going on. I am using ghc 7.4.1 (Glasgow Haskell Compiler, version 7.4.1, step 2, downloadable GHC version 7.4.1) and ubuntu linux.

I appreciate if anyone can understand why it doesn't compile with the module definition

+6
source share
3 answers

GHC compiles the Main.main function as the entry point of the executable file. When you omit a module declaration, Module Main where implicitly inserted for you.

But when you explicitly call it something other than Main ghc, the entry point is not detected.

My usual workflow is to use ghci (or ghci + emacs) instead of these snippets, which completely circumvent this problem. Alternatively, you can compile with -main-is Comma to explicitly tell ghc to use the Comma module.

+9
source

File not created

Are you sure? I expect at least Comma.o and Comma.hi . The former contains compiled code ready to connect to the executable, and the latter contains the interface information that ghc uses for typecheck modules that import the Comma module.

However, ghc will only bundle compiled modules into an executable file if there is a main function. By default, this means a function named main in a module named main . If you do not provide an explicit module name, this is assumed to be main , and why your test works when you delete the module Comma where .

To compile and link the Comma.hs file, you can use module Main where instead of module Comma where , or you can use the -main-is flag to tell ghc that Comma.main should be the main function:

 ghc --make -main-is Comma Comma.hs 

Or:

 ghc --make -main-is Comma.main Comma.hs 
+5
source

If you have a definition of main in your file, and you want to compile it into an executable, you may only need module Main where .

+1
source

Source: https://habr.com/ru/post/950384/


All Articles