Basics and Local Setup
This chapter covers the basic structure of every C program by writing and compiling the traditional “Hello, World!” program.
1. The Source Code (main.c)
In your previously created main.c file, type the following code exactly:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
2. Line-by-Line Explanation
The six lines above form the skeleton for nearly every single C program you will write.
| Code Line | Description | Purpose |
#include <stdio.h> | Preprocessor Directive | Tells the C Preprocessor to include the contents of the Standard Input/Output library (stdio.h). This file contains the declaration for the printf function. |
int main() | The Main Function | This is the required entry point of every C program. The operating system starts execution here. int means the function will return an integer value upon completion. |
{ and } | Function Body | These curly braces define the block of code that belongs to the main function. |
printf("Hello, World!\n"); | Output Statement | A function call from the stdio.h library that prints the string literal to the console. The \n is a newline escape sequence, moving the cursor to the next line. |
return 0; | Return Value | Exits the main function and returns the integer value 0 to the operating system. In C, returning 0 conventionally signals that the program executed successfully. |
3. Compiling the Program
After saving the main.c file, you need to use the GCC compiler to create an executable file. This is done from your terminal.
The Compilation Command
We use the -o option to specify the name of the output executable file (e.g., hello). If you omit the -o option, the compiler defaults the executable name to a.out (or a.exe on Windows).
gcc main.c -o hello
4. Running the Program
Once the compilation is successful, a new executable file named hello will appear in your directory. To execute it, you must reference it using the path to the current directory (./).
The Execution Command
./hello
Expected Output
Hello, World!
Review: The entire workflow is: Write code (
main.c) $\rightarrow$ Compile (gcc) $\rightarrow$ Execute (./hello).
