Skip to content

Makefile

A Makefile is a configuration file for the make program. This program will execute a sequence of instructions to compile a program.

Why use make instead of just a bash script? Because make will try and compile only what is required instead of rebuilding everything which can save some time on big projects.

Here's a simple exemple of a C++ program that uses the CPLEX library.

CFLAGS=-Wall -O
#CFLAGS=-Wall -g
CPPFLAGS=-DNDEBUG -DIL_STD
CXX=g++
OBJ=progC.o progC2.o

progC: $(OBJ)
    $(CXX) $(CFLAGS) -o progC $(OBJ)  -lm -lilocplex -lconcert -lcplex -lpthread

progC.o: progC.cpp
    $(CXX) $(CFLAGS) $(CPPFLAGS) -c progC.cpp

progC2.o: progC2.cpp
    $(CXX) $(CFLAGS) $(CPPFLAGS) -c progC2.cpp

clean:
    rm -f progC progC.o

The lines starting with # are comments and are ignored. The lines with = are variable affectation. You can use those variables with the syntax $(VARIABLE).

For exemple on line 1 the CFLAGS variable is defined and used on line 8. The variable CPPFLAGS defines options for the C++ preprocessor, in this case to specify some options that CPLEX needs. CXX defines the name of the program that can compile C++ code.

A line to build something in a makefile has a structure:

target: dependancies command

Before each command, there's TAB character. The target is what you want to create, the dependancies are the files needed to build the target and command, what you need to execute to build the target from the dependencies.

The make program is used to interpret and execute the instructions of a Makefile.

When you use make on the example, you'll get an output like this:

  make
  g++ -Wall -O -DNDEBUG -DIL_STD -c progC.cpp
  g++ -Wall -O -o progC progC.o progC2.o   -lm -lilocplex -lconcert -lcplex -lpthread

The progC program is generated. If you use make again, nothing will be done and you'll get a message similar to this: make: Nothing to be done for `progC'.

That's because the source wasn't modified so there's nothing to do.

To force a rebuild, you can use the clean target and recompile.

make clean
make