Why use Makefile?

Let’s consider a simple C program.

If you want to compile this program using gcc, you probably have to do the following:

$ gcc -c factorial.c
$ gcc -c main.c
$ gcc -o factorial main.o factorial.o

$ ./factorial
Enter a positive number: 3
Factorial of 3 is 6

Now, if you change main.c, factorial.c, or factorial.h, you would need to re-compile those files manually. This is a cumbersome process, especially when the number of files is big.

The solution is to automate the compilation process by using Makefile.

Using Makefile

A Makefile is a file that contains rules used to compile files. Essentially, it is a building recipe.
A Makefile must be named “Makefile”.

Syntax of a Makefile rule:

<target>: <prerequisites>
  • <target> is a file you want to generate.

  • <prerequisites> are files required in order to generate <target>.

    • If a prerequisite file does not exist already, Makefile will attempt to generate the file.

  • <command> is a command to be used to generate <target>.

Here is a Makefile for the simple program.

To run a Makefile, you simply type make in your terminal.

$ make
gcc -c main.c
gcc -c factorial.c
gcc -o factorial main.o factorial.o

It is important to note that a Makefile will only try to create the first <target> listed. So if you want to generate multiple files, you have to use a special rule called all. A Makefile will generate all the files listed after all.

Also, you might want a way to quickly delete object files, executables, or some other files generated by a Makefile. To achieve this, you use clean.

Here is an advanced Makefile that uses clean and all rules.

To run clean rule, you type make clean in your terminal.