C program structure
Before we look at the basic building blocks of the C language, let's take a look at a minimal C program structure that we can use as a reference in the following chapters.
C Hello World Example
C program mainly includes the following parts:
Preprocessor instructions
Function
Variable
Statement & Expression
Comments
Let us look at a simple code that can output the word "Hello World":
#include <stdio.h>int main(){ /* 我的第一个 C 程序 */ printf("Hello, World! \n"); return 0;}
Next we will explain the above program:
The first line of the program#include <stdio.h> is a preprocessor directive that tells the C compiler to include the stdio.h file before actual compilation.
Next line int main() is the main function, and the program execution starts from here.
The next line /*...*/ will be ignored by the compiler, and the comment content of the program is placed here. They are called comments for the program.
Next line printf(...) is another function available in C that displays the message "Hello, World!" on the screen.
Next line return 0; Terminate the main() function and return the value 0.
Compile & Execute C Program
Next let’s see how to save the source code in a file, and how to compile and run it. Here are the simple steps:
Open a text editor and add the above code.
Save the file as hello.c.
Open the command prompt and enter the directory where the file is saved.
Type gcc hello.c, press Enter, and compile the code.
If there are no errors in the code, the command prompt will jump to the next line and generate the a.out executable file.
Now, type a.out to execute the program.
You can see "Hello World" displayed on the screen.
$ gcc hello.c $ ./a.outHello, World!
Make sure you have the gcc compiler in your path, and make sure you are running it in the directory containing the source file hello.c.