In this example, we have a C++ project with the following files:
main()
function that drives the program.Steps to create a Makefile:
Makefile
in the same folder as your .cpp
and .hpp
files.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:
-std=c++17
— Use the C++17 standard.-g
— Include debugging information.-Wall
— Enable all warnings.-O2
— Optimize performance.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.
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.
$(CXX)
— Represents the compiler (e.g., g++
).$(CXXFLAGS)
— Compiler flags that control the compilation process, such as optimization and warnings.-c
— Indicates that the source file should be compiled into an object file without linking.-o $@
— Specifies the output file, where $@
is the target (the object file).$<
— Represents the first prerequisite (the source file being compiled).The rule for linking the object files into the final executable:
$(PROG): $(OBJS) $(CXX) $(CXXFLAGS) -o $@ $(OBJS)
To clean and rebuild the project:
clean: rm -rf *.o main rebuild: clean all
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
make
make clean
make rebuild
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.
Author: Georgina Woo