DM560, Introduction to Programming in C++

File-based dependency-tracking build systems

The make utility automatizes the build process of a program in Linux and MacOsx/Darwin. It automatically determines which pieces of a large program need to be recompiled, and issues commands to recompile them.

You need a file called a makefile or Makefile to tell make what to do. Most often, the makefile tells make how to compile and link a program.

You find an extensive description of how to prepare a Makefile at the GNU Make page. In fact sections 2 and 4 there could be enough. Here, we look at a Makefile example tailored for this course. This makefile (the name can be capitalized or not with no difference) consists of a set of variable definition and a set of targets. A target is defined by a word followed by :. The indented lines following a target definition provide the implementation of the tasks to be accomplished by the target. The indentation is important.

CXX=g++ -std=c++14 

# Flags for Debug mode:
CXXFLAGS=-g -Wfatal-errors -fsanitize=address -fsanitize=leak -fsanitize=undefined
# -g is for creating debugging symbols
# -Wfatal-errors interrupts compilation after first error
# -fsanitize adds fences to detect at run time wrong access to memory, memory leakage and undefined behaviour as in zero division, overflow, casting issues.

#Flags for Release mode:
#CXXFLAGS=-O3

INCLUDE_DIR=.
LIB_DIR=.

DEPS = Token.h
OBJ = Token.o main.o 

%.o: %.cpp $(DEPS)
	$(CXX) -I$(INCLUDE_DIR) $(CXXFLAGS) -c -o $@ $< 

calculator: $(OBJ)
	$(CXX) -L$(LIB_DIR) -o $@ $^ $(CFLAGS)

clean:
	rm -f *.o *~ calculator

In the example above, the variables are as follows:

  • INCLUDE_DIR contains the path to the header files of the program that are to be listed in the DEPS variable.
  • LIB_DIR contains the path to the directory where the library files are to be found. Explicit external libraries are to be specified adding -lname_of_lib.
  • DEPS: contains the list of headers that are included
  • OBJ contains the object files to be created and linked.

It should be easy to adapt the example to your case. In most of the cases it should be enough to copy and paste the code above, edit the OBJ and DEPS and change the name of the target.

To execute type from command line:

make calculator

The target clean is to clean up the working directory from temporary files.

This short article by Mike Bostok discusses the advantages of using make also in other contexts.

Misc

Here you can find the complete manual to GNU Make. Alternatives are Rake and Waf.

To call make in sub directories:

all:
	$(MAKE) -C lib clean

See also Recursive Use.