Last active
May 24, 2024 08:53
-
-
Save zobayer1/7265c698d1b024bb7723bc624aeedeb3 to your computer and use it in GitHub Desktop.
Generic Makefile for C++ projects with multiple cpp and h files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Pre-compiler and Compiler flags | |
CXX_FLAGS := -Wall -Wextra -std=c++17 -ggdb | |
PRE_FLAGS := -MMD -MP | |
# Project directory structure | |
BIN := bin | |
SRC := src | |
LIB := lib | |
INC := include | |
MAINFILE := $(SRC)/main.cpp | |
# Build directories and output | |
TARGET := $(BIN)/main | |
BUILD := build | |
# Library search directories and flags | |
EXT_LIB := | |
LDFLAGS := | |
LDPATHS := $(addprefix -L,$(LIB) $(EXT_LIB)) | |
# Include directories | |
INC_DIRS := $(INC) $(shell find $(SRC) -type d) | |
INC_FLAGS := $(addprefix -I,$(INC_DIRS)) | |
# Construct build output and dependency filenames | |
SRCS := $(shell find $(SRC) -name *.cpp) | |
OBJS := $(subst $(SRC)/,$(BUILD)/,$(addsuffix .o,$(basename $(SRCS)))) | |
DEPS := $(OBJS:.o=.d) | |
# Run task | |
run: build | |
@echo "🚀 Executing..." | |
./$(TARGET) $(ARGS) | |
# Build task | |
build: clean all | |
# Main task | |
all: $(TARGET) | |
# Task producing target from built files | |
$(TARGET): $(OBJS) | |
@echo "🚧 Building..." | |
mkdir -p $(dir $@) | |
$(CXX) $(OBJS) -o $@ $(LDPATHS) $(LDFLAGS) | |
# Compile all cpp files | |
$(BUILD)/%.o: $(SRC)/%.cpp | |
mkdir -p $(dir $@) | |
$(CXX) $(CXX_FLAGS) $(PRE_FLAGS) $(INC_FLAGS) -c -o $@ $< $(LDPATHS) $(LDFLAGS) | |
# Clean task | |
.PHONY: clean | |
clean: | |
@echo "🧹 Clearing..." | |
rm -rf build | |
# Include all dependencies | |
-include $(DEPS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had to remove both from the
# Compile all cpp files
section. I do have them set to something. But it seems those flags were only used in# Task producing target from built files
.