Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Program Structure

C Program Structure

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

C Hello World Example

A C program mainly consists of the following parts:

Let's look at a piece of simple code that can output the words "Hello World":

Example

#include

<

stdio.h

int

main

(

)

{

/*

My first C program

*/

printf

(

"

Hello, World!

\

n

"

)

;

return

0

;

}

Next, let's explain the program above:

  1. The first line of the program #include is a preprocessor directive, telling the C compiler to include the stdio.h file before actual compilation.
  2. The next line int main() is the main function, where program execution begins.
  3. The next line /.../ will be ignored by the compiler; here the comments of the program are placed. They are called the comments of the program.
  4. The next line printf(...) is another available function in C, which displays the message "Hello, World!" on the screen.
  5. The next line return 0; Terminates the main() function and returns the value 0.

Compiling & executing a 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:

  1. Open a text editor and add the code above.
  2. Save the file as hello.c.
  3. Open the command prompt and navigate to the directory where the file is saved.
  4. Type gcc hello.c, and press Enter to compile the code.
  5. If there are no errors in the code, the command prompt will move to the next line and generate a.out (on Windows, a.exe is generated) an executable file.
  6. Now, type a.out to execute the program (on Windows, type a.exe).
  7. You can see the following displayed on the screen: "Hello World".


$ gcc hello.c

$ ./a.out

Hello, World!

Please make sure the gcc compiler is included in your path, and make sure you run it in the directory containing the source file hello.c.

If there are multiple C source code files, the compilation method is as follows:

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

$ ./main.out

test1.c and test2.c are two source code files.