3.6. Make

This information is provided in case you want it. Makefiles will be provided for you.


Make and makefiles

Imagine that a piece of software has 100 modules. In order to compile and link it, you do not want to have to type 101 commands! You do not even want to type two commands. One should be enough.

There is a tool called make that makes it easy to compile and link large pieces of software. It relies on a file, called Makefile, that tells it what to do. Here are two basic features of makefiles.

Rules

A rule tells make how to build a particular target. Typically, a target is a file name. The form of a rule is
  target: dependencies
	command
	...
	command
The dependencies are other targets or source files on which this target depends, written one after another, separated by spaces. The commands tell what to do to build the target. For example, rule
  main.o: main.cpp tools.h stuff.h
	g++ -Wall -g -c main.cpp
says that file main.o depends on main.cpp, tools.h and stuff.h. (If any of those files is modified, main.o needs to be rebuilt.) It also gives a command that will build main.o. Each command must be preceded by a tab character. That is how make determines that it is a command.

When asked to build a target T, make does the following.

  1. It builds each of the things in the list of depencencies that is a target in the Makefile.

  2. If T is a file then, for each of the dependencies that is a file, make gets the modification time of the file. If any of the dependencies was modified more recently than the target then make performs the commands.

    It the target is not a file, then it always performs the commands.

For example, rule

  main.o: main.cpp tools.h stuff.h
	g++ -Wall -g -c main.cpp
tells make to recompile main.cpp (building main.o) if any of main.cpp, tools.h or stuff.h was modified more recently than main.o.


Definitions

Definitions allow you to simplify rules and to avoid writing the same thing several times. A definition
  NAME = TEXT
defines $(NAME) to stand for the given text. For example,
  CC     = g++
  CFLAGS = -Wall -g -c
tells make that
	$(CC) $(CFLAGS) main.cpp
should be replaced by
	g++ -Wall -g -c main.cpp

Makefiles are provided for all of the assignments. See makefile for assignment 1, makefile for assignment 2 and makefile for assignment 3. makefile for assignment 4. makefile for assignment 5. makefile for assignment 6. makefile for assignment 7.

You will do well to create Makefiles for the other assignments.


Making a target

Command

  make tgt
reads file Makefile and builds target tgt, according to what Makefile says to do. Command
  make
builds the first target listed in Makefile.


Exercises

  1. What name should you use for a makefile? Answer

  2. What does a makefile describe? Answer

  3. How can you define a target called clean that does not have any dependencies and, when made, causes files main.o and tools.o to be removed? Answer

  4. What command builds target clean? Answer