Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

C Program structure


May 11, 2021 C


Table of contents


C Program structure

Before we learn the basic building blocks of the C language, let's look at a minimal C program structure, which we can use as a reference in the next chapter.

C Hello W3Cschool instance

C The program consists mainly of the following sections:

  • Preprocessor instructions
  • Function
  • Variable
  • Statements and expressions
  • Comments

Let's look at a simple piece of code that outputs the Hello W3Cschool!

#include <stdio.h>

int main()
{
   /* 我的第一个 C 程序 */
   printf("Hello, W3Cschool! \n");
   
   return 0;
}

Let's take a look at the above procedure:

  1. The first line #include <stdio.h> preprocessor instruction that tells the C compiler to include the stdio.h file before actually compiling.
  2. The next int main() the main function, and the program starts here.
  3. The next line /*...*/ They are called comments for programs.
  4. The next line printf(...) another function available in C that displays the message Hello, W3Cschool!
  5. Next line return 0; Terminates main() function and returns a value 0

Compile and execute the C program

Let's take a look at how to save the source code in a file and how to compile and run it. Here are the simple steps:

  1. Open a text editor and add the above code.
  2. Save the file hello.c
  3. Open the command prompt and go to the directory where the file is saved.
  4. Type gcc hello.c the carriage return, and compile the code.
  5. If there are no errors in the code, the command prompt jumps to the next line and is generated a.out (in linux operating ) executable file.
  6. Now, type a.out execute the program.
  7. You can see Hello Hello W3Cschool screen.
$ gcc hello.c
$ ./a.out
Hello, W3Cschool!

Make sure that the gcc compiler is included in your path and that you run hello.c source file hello.

If it is the source file for more than one c code, compile as follows:

$ gcc test1.c test2.c -o main.out
$ ./main.out