Sunday, November 6, 2011

The ‘Hello Linux’ Program in C language

As with any new platform we would begin our journey in the Linux world by creating a ‘hello world’ program. Here is the source code....

int main( )
{
printf ( "Hello Linux\n" ) ;
return 0 ;
}

The program is exactly same as compared to a console program under DOS/Windows. It begins with main( ) and uses printf( ) standard library function to produce its output. So what is the difference? The difference is in the way programs are typed, compiled and executed. The steps for typing, compiling and executing the program are discussed below.

The first hurdle to cross is the typing of this program. Though any editor can be used to do so, we have preferred to use the editor called ‘KWrite’. This is because it is a very simple yet elegant

editor compared to other editors like ‘vi’ or ‘emacs’. Note that KWrite is a text editor and is a part of K Desktop environment (KDE). Installation of Linux and KDE is discussed in Appendix H. Once KDE is started select the following command from the desktop panel to start KWrite:
K Menu | Accessories | More Accessories | KWrite
If you face any difficulty in starting the KWrite editor please refer Appendix H. Assuming that you have been able to start KWrite successfully, carry out the following steps:

(a) Type the program and save it under the name ‘hello.c’.

(b) At the command prompt switch to the directory containing ‘hello.c’ using the cd command.

(c) Now compile the program using the gcc compiler as shown below:
# gcc hello.c

(d) On successful compilation gcc produces a file named ‘a.out’. This file contains the machine code of the (e) program which can now be executed.

Execute the program using the following command.
# ./a.out

(f) Now you should be able to see the output ‘Hello Linux’ on the screen.
Having created a Hello Linux program and gone through the edit-compile-execute cycle once let us now turn our attention to Linux specific programming. We will begin with processes.

No comments:

Post a Comment