- A C Program basically consists of the following parts:
- Preprocessor
- Functions
- Variables
- Comments
A C Program always starts executing in a special function called main()
function. Let’s take a look at a
simple C code that would print the words “Hello World”
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
- Let's examine the program:
- The first line of the program
#include <stdio.h>
is a preprocessor command, which tells the C compiler to include stdio.h file before going to compilation - The next line
int main()
is the main function where the program execution begins - The next line
/* ... */
is a comment in C and will be ignored by the compiler - The next line
printf(...)
is another function declared in stdio.h file which will display the message "Hello, Word!" - The next line
return 0;
terminates the main() function and returns the value 0
Compile and Execute C Program in Linux
Open a text editor, copy and paste the above code. Save the file as hello.c. Open a command prompt and go to the directory where you’ve saved the file.
If you’re using gcc compiler, you type gcc hello.c
and press enter to compile your code. If there are no errors in your code, it would generate a.out executable file. Now, type a.out to execute your program and you will see the output “Hello, World!”.
If you’re using clang compiler, you type clang hello.c
and press enter to compile your code. If there are no errors in your code, it would generate a.out executable file. Now, type a.out to execute your program and you will
see the output “Hello, World!”.