Makefiles for C++

Download PDF

1. Understanding the Project Structure

In this example, we have a C++ project with the following files:

2. Making the Makefile

Steps to create a Makefile:

  1. Create a new file named Makefile in the same folder as your .cpp and .hpp files.
  2. Define the compiler and compilation flags:
CXX = g++
CXXFLAGS = -std=c++17 -g -Wall -O2
    

Important: The Makefile must be placed in the same directory as your source files (.cpp) and header files (.hpp) for the compilation process to work correctly.

Explanation:

3. Defining the Target and Object Files

PROG ?= main
OBJS = Class.o main.o

Explanation: PROG is the name of the executable, and OBJS are the compiled object files.

Essentially, we want to create an executable that can later be run using ./main. To achieve this, we first compile individual source files into object files (.o), which are then linked together to produce the final executable.

4. Compiling Source Files

The rule for compiling source files:

.cpp.o:
$(CXX) $(CXXFLAGS) -c -o $@ $<

Explanation: This rule tells make how to compile a .cpp file into a corresponding .o (object) file.

5. Linking Object Files

The rule for linking the object files into the final executable:

$(PROG): $(OBJS)
    $(CXX) $(CXXFLAGS) -o $@ $(OBJS)

6. Adding Clean and Rebuild Rules

To clean and rebuild the project:

clean:
    rm -rf *.o main

rebuild: clean all

7. Final Makefile

CXX = g++
CXXFLAGS = -std=c++17 -g -Wall -O2

PROG ?= main
OBJS = Class.o main.o

all: $(PROG)

.cpp.o:
    $(CXX) $(CXXFLAGS) -c -o $@ $<

$(PROG): $(OBJS)
    $(CXX) $(CXXFLAGS) -o $@ $(OBJS)

clean:
    rm -rf *.o main

rebuild: clean all

8. Using the Makefile

9. Extending the Makefile

Modifying the Makefile to include a subclass:

PROG ?= program
OBJS = Class.o Subclass.o main.o

clean:
    rm -rf *.o program

# The rest of the Makefile remains the same.

10. References

Author: Georgina Woo