-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMakefile
More file actions
66 lines (53 loc) · 2.24 KB
/
Makefile
File metadata and controls
66 lines (53 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Lesson 17: Functions & Auto-Discovery
#
# Key functions:
# $(wildcard pattern) — expand glob, return matching files
# $(patsubst from,to,text) — pattern substitution
# $(filter pattern,text) — keep only matching words
# $(filter-out pattern,text) — remove matching words
# $(foreach var,list,body) — loop over a list
# $(call name,args...) — invoke a user-defined function
# $(sort list) — sort and deduplicate
# $(words list) — count words in list
#
# The big idea: auto-discover source files instead of listing them manually.
# Add a new .cpp to src/ and it's automatically compiled — no Makefile edits.
CXX = g++
CXXFLAGS = -std=c++20 -Wall -Wextra -Iinclude -MMD -MP
BUILDDIR = build
# ── Auto-discovery ───────────────────────────────────────
# $(wildcard) finds all matching files — no manual list needed
SRCS = $(wildcard src/*.cpp)
# $(filter-out) removes main.cpp so we can link it separately if needed
LIB_SRCS = $(filter-out src/main.cpp, $(SRCS))
# $(patsubst) is the full form of substitution references
# These two lines are equivalent:
# OBJS = $(SRCS:%.cpp=$(BUILDDIR)/%.o)
# OBJS = $(patsubst %.cpp,$(BUILDDIR)/%.o,$(SRCS))
OBJS = $(patsubst %.cpp,$(BUILDDIR)/%.o,$(SRCS))
DEPS = $(OBJS:.o=.d)
TARGET = $(BUILDDIR)/app
# ── User-defined function with $(call) ───────────────────
# $(1) is the first argument passed to the function
announce = @echo "── $(1) ──"
# ── Targets ──────────────────────────────────────────────
.PHONY: all clean info
all: $(TARGET)
$(TARGET): $(OBJS)
@mkdir -p $(@D)
$(call announce,Linking $@)
$(CXX) -o $@ $^
$(BUILDDIR)/%.o: %.cpp
@mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
rm -rf $(BUILDDIR)
# ── Info target: show what the functions resolved to ─────
info:
@echo "SRCS = $(SRCS)"
@echo "LIB_SRCS = $(LIB_SRCS)"
@echo "OBJS = $(OBJS)"
@echo ""
@echo "File count: $(words $(SRCS)) source files"
@echo "Sorted: $(sort $(SRCS))"
-include $(DEPS)