Can ghc automatically run the executable?

Starting out with ghc. Compiled and ran my first few scripts. And now I have a very simple, practical question:

Can ghc run the executable after compiling (and linking)?

I looked at ghc's options, but couldn’t find any suitable command line flag.

Try using ghci instead:

# cat Query.hs

main = putStrLn "Can ghc automatically run the executable?"

# ghci -fobject-code -e "main" Query.hs
Can ghc automatically run the executable?
# ls Query.*
Query.hi  Query.hs  Query.o
#

If you don’t want those extra files, use runghc:

#  runghc --help
Usage: runghc [runghc flags] [GHC flags] module [program args]

The runghc flags are
    -f /path/to/ghc       Tell runghc where GHC is
    --ghc-arg=...         Pass an option or argument to GHC
    --help                Print this usage information
    --version             Print version number
#
1 Like

You can also just do it in your shell (assuming you’re on Linux/macOS):

$ ghc Main.hs -o Main && ./Main

Thanks for this. runghc is exactly what I was after!

Note that runghc doesn’t compile your programs. It runs programs using the interpreter (like GHCi), which is much slower at run time but faster at compile time.

1 Like

Furthermore, you could read this re scripting using Haskell:

Good to know! I wasn’t aware of that.

That’s why there’s no extra files - they’re never generated to begin with. runghc is best used for small tasks and projects - larger ones are better served by @jaror’s or @hellwolf’s suggestions.