Compilation refers to the process of converting a program form the textual source code, in a programming a language such as C or C++ , into machine code, the sequence of 1’s and 0’s used to control the central processing unit(CPU) of the computer. This machine code is then store in a file known as an executable file, sometimes referred to as a binary file.


1. Compiling a simple C program


The option -Wall turns on all the most commonly-used compiler warning.


2. Compiling multiple source files


A program can be split up into multiple files. This makes it easier to edit and understand, especially in the case of large programs — it allows individual parts to be compiled independently.

Here is the main program ‘main.c':

The declaration in ‘hello.h’ is a single line specifying the prototype of the function hello:

The definition of the function hello itself is contained in the file ‘hello_fn.c':

To compile these source files with gcc:

To run the program, type the path name of the executable:


3. Compiling files independently


The command-line option -c is used to compile a source to an object file.

When compiling with -c the compiler automatically creates an object file whose name is the same as the source file, but with ‘.o’ instead of the original extension.
There is no need to put the header file on the command line, since it is automatically included by the #include statements in ‘main.c’ and ‘hello_fn.c’.


4. A simple makefile


Make reads a description of a project from a makefile (by default, ‘Makefile’ in the current directory). A makefile specifies a set of compilation rules in terms of targets (such as executables) ¬†and their dependencies (such as object files and source files) in the following format:

Note that the command lines in a makefile must be indented with a single TAB character, not spaces.
GNU Make contains many default rules, referred to as implicit rules, to simplify the contruction of makefiles.Implicit rules are defined in terms of make variables, such as cc (the C compiler) and CFLAGS ( the compilation options for C programs), which can be set using VARIABLE=VALUE lines in the makefile.
The implicit and user-defined rules are automatically chained together as necessary by GNU make.
A simple ‘Makefile’ for the project above can be written as follows:

5. Linking with external Libraries

is equivalent to the original command using the full library name ‘/usr/lib/libm.a’.