19

I wrote a simple module called Test:

module Test (main) where

main =
  putStrLn "Hello"

However, when i try to compile it via the following command line:

ghc Test.hs -o my-program

I get the following error:

[1 of 1] Compiling Test             ( Test.hs, Test.o )

<no location info>: error:
    output was redirected with -o, but no output will be generated because there is no Main module.
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Alex Goft
  • 1,114
  • 1
  • 11
  • 23

2 Answers2

35

ghc will assume that the main is located in a module called Main (like the compiler says).

ghc however has an option -main-is where you can specify the name of the module where the main function is located. So you can compile with:

ghc -main-is Test Test.hs -o my-program
Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 10
    This answer is also useful in the case where you are using `stack` and trying to add a second executable in `package.yaml` with `main: App.hs`. `stack build` will fail with the same error as the title of this post, which bought me here :). So the solution is to add a `- -main-is App` in `ghc-options` section. Just to share in case someone came here with the same case as mine. – Leo Zhang Oct 26 '18 at 14:07
  • 7
    What's the point of having a `main-is` section in the cabal file if is not respected? – Saurabh Nanda Dec 20 '18 at 06:47
  • @SaurabhNanda One may argue that the `main-is` param. in the cabal file expects a .hs or .lhs file, that is an actual file. That doesn't say anything about the name of the module this file may contain (here, one may also argue that module names and filenames/paths are meant to have a strong relationship within a project: eg. one can have a file src/Foo/Bar.hs containing a module named `Foo.Bar` but not `Foo.Baz` but this differs from that standard.) Thus from a cabal perspective this seems to be the filename, and from GHC's perspective, it must be the module name. – Ashesh Jun 24 '20 at 09:16
17

I had the same problem, but in my case I had caused it by adding a module name to the test source file, test/Spec.hs:

module Tests where

main :: IO ()
main = hspec $ do ...

The solution was simply removing the first line:

main :: IO ()
main = hspec $ do ...

This is also the default when you create a project with stack - e.g., stack new myproject.

Milad
  • 836
  • 7
  • 13
  • 1
    Thanks, that fixed my issue! Do you know what exactly is causing it? Why test files shouldn't be defined as modules? – mjarosie Nov 19 '19 at 23:37
  • No sorry, I actually don’t know the reason, and to say the truth I haven’t given much time to the matter ;) – Milad Nov 20 '19 at 19:47
  • 1
    I've posted a question here: https://stackoverflow.com/q/58944736 – mjarosie Nov 21 '19 at 00:21