Basic Makefiles

The Unix make utility can be used to automate the compilation and linking of programs. We introduced make in the first lab of the semester, but it may have been difficult to see how useful it could be when you had only written very simple programs; now that you have written more complex, multi-file programs, you will appreciate make's functionality.

make requires that the programmer provide instructions to build the program in a text file called a makefile. The makefile file will typically be named Makefile with a capital "M"; the make program looks for this file by default.

A makefile consists of multiple sections, called rules, that specify how the program is built. Each rule consists of a header line, listing a specific item to build (called the target) and the files the target depends upon (the dependencies), followed by zero or more lines specifying the commands necessary to construct the target (the build actions or recipe). The target is typically a file name, such as the name of an executable program. make compares the last-modified timestamp of the target with those of its dependencies, and if any of the dependencies is newer, it will execute the recipe to bring the target up-to-date.

Here is a basic makefile example; it builds the executable program from the single souce file program.cpp:

program: program.cpp
	g++ -Wall -ansi program.cpp -o program

In this example, program is the target, program.cpp is the only dependency, and the recipe is g++ -Wall -ansi program.cpp -o program. When make is run using this Makefile, it will check to see if program.cpp has been modified more recently than program and, if so, will execute the recipe to recompile the program.

Note: the whitespace at the beginning of a recipe must be a tab. Emacs will insert a tab correctly so long as your makefile is named Makefile – Emacs knows not to replace tabs with spaces when working on makefiles.

Once the makefile has been created, the program can be built with the command

make

By default, the make command will build the first target in the makefile which, in this case, is program.