Makefiles are special compilation scripts which are read and executed by the make command. The purpose of a makefile is to assist in building a compilation pipeline for large programs. Its main advantage is ease of use combined with its tracking of updates to files (i.e. only things that have changed are re-compiled). Below you will find some helpful tips to get started.
Open a file called GNUmakefile, makefile, or Makefile in the terminal
$ vim makefile
To compile a simple file we can start by typing a directive tag followed by the compilation steps. Typically the files used in the compilation steps are listed after the directive that uses them, in this case, test.c is used in all so it is listed after all. (Note: make sure to tab all entries under a given tag)
0 all: test.c
1 gcc test.c -o test
Returning to the terminal we can now type 'make' or 'make all' to perform the compilation steps following all. (Note: omitting a specific tag will automatically run the first tag of the file)
$ make
$ make all
Makefiles are most often used with multiple directive tags and often have tags which call each other. In the example below our makefile contains an all directive which then calls our tag test and other and performs their compilation steps. (Note: the test and other tags are called first before all runs its compilation code)
0 all: test other
1 gcc test.o other.o -o test
2 test: test.c
3 gcc -c test.c -o test.o
4 other: other.c
5 gcc -c other.c -o other.o
Running make all for the above makefile is equivalent to performing the following compilation commands
$ gcc -c test.c -o test.o
$ gcc -c other.c -o other.o
$ gcc test.o other.o -o test
Typically a make clean directive is provided for ease of cleaning up the files generated during compilation. This consists of an rm call that deletes all .o files and any executables that are generated.
0 all: test other
1 gcc test.o other.o -o test
2 test: test.c
3 gcc -c test.c -o test.o
4 other: other.c
5 gcc -c other.c -o other.o
6 clean:
7 rm *.o test
Invocation of the clean directive can be done as follows:
$ make clean