# Compiler and linker configurations
CXX = g++
CXXFLAGS = -Wall -Iinclude
LDFLAGS =
# Directory structure
SRCDIR = src
BINDIR = bin
INCDIR = include
# Find all .cpp files in the src directory
SOURCES = $(wildcard $(SRCDIR)/*.cpp)
# For each .cpp file, replace the .cpp extension with .o and prefix with the bin directory
OBJECTS = $(patsubst $(SRCDIR)/%.cpp, $(BINDIR)/%.o, $(SOURCES))
# Target executable name
TARGET = $(BINDIR)/myprogram
# Default target
all: $(TARGET)
# Rule for linking the final executable
# Depends on all of the object files
$(TARGET): $(OBJECTS)
$(CXX) $(LDFLAGS) -o $@ $^
# Rule for compiling source files to object files
# Each object file depends on its corresponding source file
$(BINDIR)/%.o: $(SRCDIR)/%.cpp
mkdir -p $(BINDIR)
$(CXX) $(CXXFLAGS) -c $< -o $@
# Clean up build files
clean:
rm -f $(BINDIR)/*.o $(TARGET)
# Phony targets for clean and all to prevent conflicts with files of the same name
.PHONY: all clean
Explanation:
- Compiler Configurations: Sets the compiler (
g++
), flags for compilation (CXXFLAGS
includes theinclude
directory and enables all warnings with-Wall
), and linker flags (LDFLAGS
). - Directory Structure: Defines the source (
src
), binary (bin
), and include (include
) directories. - Source and Object Files: Locates all
.cpp
files in thesrc
directory and defines a corresponding.o
file in thebin
directory for each source file. - Target Executable: Specifies the name of the final executable (
myprogram
) and places it in thebin
directory. - Rules:
- The
all
target builds the final executable. - The rule for
$(TARGET)
links the object files to create the executable. - The rule for compiling
.cpp
to.o
files also ensures thebin
directory exists.
- The
- Clean Target: Removes all compiled files to clean up the project.
- Phony Targets: Declares
all
andclean
as phony targets to avoid conflicts with potential files of the same name.
Place this Makefile in your project’s root directory. To compile your project, just run make
in the terminal. To clean up the compiled files, run make clean
.