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
C programs mainly consist of the following parts:
- Preprocessor directive
- Function
- Variable
- Statements & expressions
- Comments
Let's look at a simple piece of code that can output the word "Hello World":
Example
#include <stdio.h>
int main()
{
/*My First C Program*/
printf("Hello, World! \n");
return 0;
}
Next, let's explain the above program:
- The first line of the program#include <stdio.h>It is a preprocessor directive that tells the C compiler to include the stdio.h file before actual compilation.
- Next lineint main()It is the main function; the program starts executing from here.
- The next line /*...*/ will be ignored by the compiler; this is where the program comments go. They are called program comments.
- Next lineprintf(...)It is another function available in C that displays the message "Hello, World!" on the screen.
- Next linereturn 0;It terminates the main() function and returns the value 0.
Compiling & executing C programs
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 ashello.c。
- Open the command prompt and go to the directory where the file is saved.
- Typegcc 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 generatea.out (Windows generates a.exe)Executable file.
- Now, typea.outto execute the program (under Windows, typea.exe)。
- You can see the following displayed on the screen:"Hello World"。
$ gcc hello.c $ ./a.out Hello, World!
Make sure your path already includes the gcc compiler, and ensure that 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.
other extensions