Latest web development tutorials

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:

  1. 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.
  2. The next lineint main ()is the main function, program execution begins here.
  3. /*...*/ Next line will be ignored by the compiler, where to place the note contents of the program. They are known as program notes.
  4. The next lineprintf (...)is a C in another available function, the message "Hello, World!" On the screen.
  5. 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:

  1. Open a text editor, add the above code.
  2. Save the file ashello.c.
  3. Open a command prompt, change to the directory to save the file.
  4. Typegcc hello.c,press enter, compile the code.
  5. If there are no errors in the code, the command prompt will jump to the next line and generatesa.outexecutable file.
  6. Now typea.outto execute the program.
  7. 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.