Skip to content

Make Tips

Makefile how-to

The general format of the makefile is:

target: dependency1 dependency2
<tab>   command to build target
  • target is what you want to build, eg: main.o
  • dependency is when to rebuild target when dependency changes, eg: main.cpp
  • command is the compiler command to build target, eg: g++

In Unix, g++ is both a compiler and a linker.

Sample makefile:

CXXFLAGS = -std=c++17 -Wall -O0 -g 
LDFLAGS = -lgtest -lgtest_main -lpthread

# by default, the first target is the default target
#
# build the executable from the binary objects

m03: memory_tests.o
    $(CXX) $^ -o $@ $(LDFLAGS)
# g++ -o m03 memory_tests.o 
#
# macro definitions
# $@    = the target
# $?    = all pre-requisites newer than the target
# #^    = all pre-requisites (dependencies)

memory_tests.o: memory_tests.cpp
# use make's default rule for building cpp into o
#    $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $^ -o $@


clean:
    rm -f *.o m03   

Compiler flags

  • C++ build command: g++ -o
  • Standards: -std=c++11, -std=c++14, -std=c++17, -std=c++20
  • Verbosity: -Wall all warnings, -Werror warnings into error, -Wextra
  • Compiler flags: -DFLAG, -DVAR=1
  • Optimisation: -O0 none, -O2, -O3 more optimisation
  • Debugging: -g build with debugging symbols for gdb debugger
  • Compile only: -c

Linker flags

  • Verbosity: -Wl
  • Libraries: -lpthread include Posix threads library, -static-libstdc++