C program structure
Before we learn the basic building blocks of C language, let's take a look at a minimum of C program structure, in the next section can serve as a reference.
C Hello World Examples
C program includes the following components:
- Preprocessor directives
- function
- variable
- Statement & Expression
- Note
Let's look at a simple piece of code, you can output the words "Hello World":
#include <stdio.h> int main() { /* 我的第一个 C 程序 */ printf("Hello, World! \n"); return 0; }
Next we explain above, this procedure:
- The first line of the program#include <stdio.h>is a preprocessor directive that tells the C compiler before the actual compilation to include stdio.h file.
- The next lineint main ()is the main function, program execution begins here.
- /*...*/ Next line will be ignored by the compiler, where to place the note contents of the program. They are known as program notes.
- The next lineprintf (...)is a C in another available function, the message "Hello, World!" On the screen.
- The next linereturn 0; termination of main () function, and returns the value 0.
Compile & C program execution
Let's look at how to save the source code in a file, and how to compile and run it. Below are simple steps:
- Open a text editor, add the above code.
- Save the file ashello.c.
- Open a command prompt, change to the directory to save the file.
- Typegcc hello.c,press enter, compile the code.
- If there are no errors in the code, the command prompt will jump to the next line and generatesa.outexecutable file.
- Now typea.outto execute the program.
- You can see on-screen display"Hello World".
$ gcc hello.c $ ./a.out Hello, World!
Make sure that your path is included gcc compiler, and make sure to run it in the directory containing the source file hello.c.