C is a widely-used programming language for various reasons. It can be compiled on various operating systems and efficient executable programs are generated. The compilation and execution of example programs of this tutorial will be shown for the Linux operating system.
Let us discuss, how to write a program in this language.
First, open a terminal and do the following (If you are not familiar with the vi editor you may read this tutorial). Open a file using a text editor (you may use vi editor). The extension of the file should be .c, not .C. If you are going to use vi editor, write the following command on your terminal.
#vi test.c
Now, write the following code in that file and save the content.
#include <stdio.h>
int main (void)
{
printf("Hello World!");
return 0;
}
Now to compile the program, use the cc or gcc command as shown below.
#cc test.c
At this time, one file will be generated by the name a.out. To run this program do the following and check the result.
#./a.out
If you want to rename the generated file (a.out), to a custom name according to your choice, you may use the following command.
#cc test.c -o expected_name
In this case, you may execute the program using the following command from the same directory location, where the file is generated.
#./expected_name
Now, we are explaining the program shown above.
#include<stdio.h> is used to include standard input and output library in this program. This library contains input/output-related functions.
In this example, we are using the printf() function (it will be discussed later in detail). This printf() function is used to print something on the terminal device.
The main() function is a special function in this language, which is the starting point of the program, however, this program is user-defined.
(Functions will be discussed later in detail.)
In this main() function in the last line, the return 0 statement is written. Remember that the main function returns a value to the operating system. Based on this value operating system understands whether the process was completed successfully or not, and the operating system takes the necessary steps.
As a developer, you should return this value, though you may get some tutorials where the return type is void. This value is required to inform the termination status of the program to the operating system so that the operating system can take necessary actions for the deallocation of the allocated resources to that process. Later on, you learn different error codes which may be returned by the program to the operating system.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.