Makefile to automate the build process for C++

CK CK 3788 
Created at  
277 0 0

Makefiles are used in C++ projects to automate the build process, especially when the project has multiple source files and dependencies. They define rules specifying how to compile individual source files into object files and then link those object files into an executable, handling dependencies automatically so that only necessary files are recompiled when changes are made. This significantly speeds up development and simplifies the build process, making it more manageable for larger and more complex projects.
 

A Makefile is a text file that contains instructions for a build system, specifically the GNU Make utility, on how to build a program or other software project. It specifies dependencies between files (e.g., object files needing source code) and the commands to execute to create target files from their dependencies. This allows for automated compilation, linking, and other build processes, greatly simplifying the development workflow, particularly for large projects with many source files.
 

Here’s a simple example of a Makefile for a basic C++ project.

Project Structure

MyProject/
├── Makefile
├── src/
│   ├── main.cpp
│   ├── my_code.cpp
└── include/
    └── my_code.h

Example: Makefile

# Compiler and flags
CXX = g++
CXXFLAGS = -Wall -Wextra -std=c++17 -Iinclude

# Project structure
SRCDIR = src
OBJDIR = obj
BINDIR = bin
TARGET = $(BINDIR)/MyProject

# Source and object files
SOURCES = $(wildcard $(SRCDIR)/*.cpp)
OBJECTS = $(patsubst $(SRCDIR)/%.cpp, $(OBJDIR)/%.o, $(SOURCES))

# Default target
all: $(TARGET)

# Create the executable
$(TARGET): $(OBJECTS) | $(BINDIR)
	$(CXX) $(CXXFLAGS) -o $@ $^

# Compile source files into object files
$(OBJDIR)/%.o: $(SRCDIR)/%.cpp | $(OBJDIR)
	$(CXX) $(CXXFLAGS) -c $< -o $@

# Create directories if they don't exist
$(OBJDIR):
	mkdir -p $(OBJDIR)

$(BINDIR):
	mkdir -p $(BINDIR)

# Clean build files
clean:
	rm -rf $(OBJDIR) $(BINDIR)

# Phony targets
.PHONY: all clean

Build Steps

  1. Navigate to the project directory:

    cd MyProject
    
  2. Run make to build the project:

    make
    
  3. Run the executable:

    ./bin/MyProject
    
  4. Clean the build files:

    make clean
    

Explanation

  1. Variables:
    • CXX specifies the compiler.
    • CXXFLAGS sets compiler flags for warnings, C++ standard, and include directories.
    • SRCDIR, OBJDIR, and BINDIR define directories for source, object, and binary files.
  2. Targets:
    • all: The default target that depends on $(TARGET).
    • $(TARGET): Links object files into the final executable.
    • $(OBJDIR)/%.o: Compiles source files into object files.
  3. Automatic Directory Creation:
    • The | $(BINDIR) and | $(OBJDIR) parts ensure directories are created before compiling.
  4. Clean:
    • Removes generated files to start fresh.

This Makefile is modular and suitable for small-to-medium-sized projects. It avoids hardcoding and works dynamically with the files in the src directory.

Tags C++ C++ Project Makefile Facebook X
Comments 0
Similar posts
  1. How to call SetTimer function on MFC CDialog class ?
    650
  2. How to load HTML resource on MFC ?
    839
  3. URL Encode, Decode function for MFC
    603
  4. How to search file on certain directory ?
    627
  5. How to run shell command by MFC ?
    434
  6. Binary Search Sample Code
    403
  7. Double Linked List based in C++
    796
  8. MFC based World Wide Web HTTP Server Source Code
    458
  9. Creating and Using a CAsyncSocket Object to use CAsyncSocket
    470
  10. Fast and Good Keyboard/Mouse Test without the message handler
    975
  11. Simple CGI Programming in C
    541
  12. C++ CGI Example working on Apache
    481
  13. KMP String Matching Algorithm
    670
  14. CMake - a cross-platform build system generator that creates Makefiles used in C++ projects
    293
  1. KMP String Matching Algorithm
    670
  2. How to get process id in C# like windows task manager ?
    867
  3. How to implement switch statement in C# ?
    985
  4. How to implement while loop in C# ?
    1,337
  5. How to delete file ?
    1,188
  6. How to convert integer to text string ?
    696
  7. How to convert text string to integer ?
    608
  8. How to set an certain color as transparent color on bitmap
    508
  9. How to resize and save PNG or Jpeg Image file ?
    629
  10. How to display message box in C#
    1,104
  11. How to convert bitmap image to jpeg image ?
    353
  12. To load image from file
    446
  13. URL Encode, Decode function for MFC
    603
  14. How to load HTML resource on MFC ?
    839
  15. How to get GM Time as String ?
    422
  16. Finding process name on OS
    405
  17. Convert System.DateTime to UNIX timestamp
    380
  18. Retrieve system information
    494
  19. How to call SetTimer function on MFC CDialog class ?
    650
  20. How to rename(change file name) in C# ?
    1,072
  21. Find Files in certain directory
    924
  22. Implementing C#'s foreach loop in Delphi 8
    459
  23. How to detect resource leaks in a Form
    936
  24. The best way to enable and disable buttons, menu items and toolbar buttons
    667
  25. How to exit from a console application
    809
  26. How to restrict a program to a single instance
    727
  27. Compress and decompress strings in C#
    970
  28. Graphics in C# - Irregular Forms
    906
  29. Extracting the Country from IP Address
    466
  30. How to run shell command by MFC ?
    434
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,727
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    232
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252