Friday, 29 April 2016

Haskell: Hello World program using ghc command

ghc compiler comes as part of GHC distribution. Ghc command takes a Haskell file and generates native code.


hello_world.hs
main = putStrLn ("hello, world")


Use the command ‘ghc hello_world.hs’ to generate executable.
$ ls he*
hello_world.hs
$ ghc hello_world.hs
[1 of 1] Compiling Main             ( hello_world.hs, hello_world.o )
Linking hello_world ...
$ 
$ ls he*
hello_world hello_world.hi hello_world.hs hello_world.o
$ 


Observe above snippet, ghc command generates three new files.
File
Description
hello_world
Executable file.
hello_world.hi
It is just an interface file, stores information about the names exported from our module in machine-readable form. Don't worry about modules at this point of time; modules are used to logically organize our code.
hello_world.o
Object file, which contains machine code.

Call the executable file to see the result of hello_world.hs.

$ ./hello_world
hello, world


Some times you want to generate only object file, don’t want to generate executable, in that case use the option –c.

$ rm hello_world.hi hello_world.o hello_world
$ ls he*
hello_world.hs
$ 
$ ghc -c hello_world.hs
$ ls he*
hello_world.hi hello_world.hs hello_world.o


Use the command 'ghc --help' to get the help about ghc compiler.




Previous                                                 Next                                                 Home

No comments:

Post a Comment