Using make to compile

# Compiler and linker configurations
CXX = g++
CXXFLAGS = -Wall -Iinclude

# 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
	$(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
	rm -f $(BINDIR)/*.o $(TARGET)

# Phony targets for clean and all to prevent conflicts with files of the same name
.PHONY: all clean


  1. Compiler Configurations: Sets the compiler (g++), flags for compilation (CXXFLAGS includes the include directory and enables all warnings with -Wall), and linker flags (LDFLAGS).
  2. Directory Structure: Defines the source (src), binary (bin), and include (include) directories.
  3. Source and Object Files: Locates all .cpp files in the src directory and defines a corresponding .o file in the bin directory for each source file.
  4. Target Executable: Specifies the name of the final executable (myprogram) and places it in the bin directory.
  5. 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 the bin directory exists.
  6. Clean Target: Removes all compiled files to clean up the project.
  7. Phony Targets: Declares all and clean 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.