The Unix make utility can be used to automate the compilation and linking of programs. It may be difficult to see how this could be useful at this point, but you will appreciate make's functionality when you work on complex, multi-file projects later in the semester. For now, we will learn how to use make for simple program builds.
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 prerequisites), 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 the prerequisites it depends on, and if any of the prerequisites is newer, it will execute the recipe to bring the target up-to-date.
Without further ado, here are the contents of a very simple makefile:
program: program.cpp g++ -Wall program.cpp -o program
In this example, program is the target, program.cpp is the only prerequisite, and the recipe is g++ -Wall 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.
Now, create a makefile (named Makefile) to build your C++ program proj0.cpp. Create the makefile in Emacs, entering the lines from the sample, modified appropriately. Once you have created the makefile, save and quit Emacs. Test the makefile by entering the following commands at the Linux prompt:
touch proj0.cpp make
The touch command changes the last-modified time of proj0.cpp to the current time, ensuring that proj0.cpp is "newer" than the executable proj0; thus the make command will execute the recipe to rebuild the executable.