Makefiles

Separate compilation - breaking code into a number of translation units (or files). A way is needed to turn these files into one executable file. One way is:

g++  file1.cc  file2.cc

The problem with this type of approach is that each file will be re-compiled whenever this command is executed.

To solve this problem, there is a program called make available on the UNIX system that can selectively compile and link files depending on a specific set of rules. The rules to follow are going to be contained in a file called a Makefile.

The basic format for rules (or dependencies) in the Makefile is:

target : dependancies
    command

make will look at the dates on the target file and its dependent file(s). If a dependent file has a newer date than the target file, make will execute the command.

As part of the dependency checking, make will first verify that the dependency is not the target of another rule. If it is, the other rule will be evaluated first. Once all of the dependencies are up to date, the comparison will be made with the current rule.

Some things to remember about rules:

  1. The rules are not steps in a program.

  2. The first rule is evaluated first if no target is explicitly specified when make is invoked.

  3. ALWAYS use tabs for indentation of commands

For example:

hello : hello.cc
    g++  hello.cc

This says that the executable file 'hello' depends on the source code file 'hello.cc'. If 'hello.cc' has a newer date than 'hello', make will execute the command 'g++ hello.cc'.

A Makefile may contain macros, which will be used for string replacement. The most common one is for the compiler.

CC = g++

The = is used to identify CC as a macro. To use the macro within the Makefile:

CC = g++

hello : hello.cc
    $(CC)  hello.cc

The $ and parenthesis will cause the macro to expand when the command is executed.

To execute the Makefile, at a UNIX prompt execute the command make.