makefile-best-practices — independently scanned and version-tracked by SaferSkills.
SaferSkills independently audited makefile-best-practices (Agent Skill) and scored it 100/100 (green). The audit ran 55 deterministic rules across Security, Supply Chain, Maintenance, Transparency, and Community; it found 0 high-severity and 0 lower-severity findings. The full rule-by-rule trace and per-finding evidence are below. Free, methodology-open.
Findings & checks · 0 flagged
Every scanned point with the score it earned and what moved between them.
First recorded scan — no prior version to compare against.
The primary manifest — the file an agent reads to learn what this artifact does.
Target: GNU Make 4.x. Covers Make as both a build system (dependency-driven compilation) and a task runner (developer workflow automation).
Targets represent outputs; prerequisites represent inputs; recipes transform inputs → outputs. Think graph-first.
# WRONG: Script thinking - order-dependent, breaks with -j
build:
compile src/a.c
compile src/b.c
link
# RIGHT: Graph thinking - declares real dependencies
program: a.o b.o
$(CC) -o $@ $^
%.o: %.c
$(CC) -c $< -o $@make -j is the Real BarIf it breaks with parallel builds, it's broken. Always declare real dependencies.
# WRONG: Hidden dependency, races under -j
generated.h:
./generate-header.sh > $@
main.o: main.c # Missing: generated.h
$(CC) -c $< -o $@
# RIGHT: Explicit dependency
main.o: main.c generated.h
$(CC) -c $< -o $@Validate dependency correctness with make --shuffle=random -j (GNU Make 4.4+). Randomizing prerequisite order exposes missing edges that a fixed order hides.
Use .PHONY for commands, not for artifacts. Understanding timestamps is 80% of Make proficiency.
.PHONY: clean test lint help # Commands - always run
# Don't mark file-producing targets as phony# := immediate (evaluated when defined) - use for $(shell), most cases
FILES := $(shell find src -name '*.c')
# = deferred (evaluated when used) - use when referencing later-defined vars
CFLAGS = $(BASE_FLAGS) $(EXTRA_FLAGS)
# ?= conditional (set only if undefined) - use for user-overridable defaults
PREFIX ?= /usr/local
CC ?= gcc$(shell ...) with = re-runs the command every time the variable is expanded — always use := for shell captures unless repeated execution is intentional.
| Variable | Meaning |
|---|---|
$@ | Target name |
$< | First prerequisite |
$^ | All prerequisites (deduped) |
$? | Prerequisites newer than target |
$* | Stem matched by % |
$(@D) | Directory part of target |
$(BUILD_DIR)/%.o: src/%.c | $(BUILD_DIR)
@mkdir -p $(@D)
$(CC) $(CFLAGS) -c $< -o $@The essential hygiene directives plus a self-documenting help target. For a production-ready template with verbosity toggle, color output, and a GNU Make 4.0+ compatibility check, see `references/Makefile.gnumake-template`.
Each line of the preamble matters:
| Directive | Effect |
|---|---|
SHELL := bash | Use bash (not /bin/sh/dash) for richer recipe syntax |
.SHELLFLAGS := -eu -o pipefail -c | Unset vars, errors, and pipe failures all abort the recipe |
.DELETE_ON_ERROR: | Remove the target file on recipe failure — prevents stale half-built artifacts |
--warn-undefined-variables | Catch typos in variable names at parse time |
--no-builtin-rules | Strip implicit rules for faster parsing and explicit semantics |
.DEFAULT_GOAL := help | Bare make prints help instead of building the first target |
SHELL := bash
.SHELLFLAGS := -eu -o pipefail -c
.DELETE_ON_ERROR:
MAKEFLAGS += --warn-undefined-variables --no-builtin-rules
.DEFAULT_GOAL := help
.PHONY: build test clean help
build: ## Build the project
go build ./...
test: ## Run tests
go test ./...
clean: ## Remove build artifacts
rm -rf build/
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}'# BAD: Rebuilds when ANY file added to dir (timestamp changes)
$(objs): $(BUILD_DIR)
# GOOD: Only checks existence, not timestamp
$(objs): | $(BUILD_DIR)
$(BUILD_DIR):
mkdir -p $@CPPFLAGS += -MMD -MP
-include $(deps)Flags: -MMD generates .d files, -MP adds phony targets for headers (prevents errors if deleted).
For rules producing multiple outputs, use &: instead of sentinel files:
# Modern: grouped target
parser.c parser.h &: parser.y
bison -d $<
# Legacy: sentinel file pattern
.parser.sentinel: parser.y
bison -d $<
touch $@
parser.c parser.h: .parser.sentinel# Different flags for different targets
debug: CFLAGS += -g -O0 -DDEBUG
debug: all
release: CFLAGS += -O3 -DNDEBUG
release: all
test: CFLAGS += -DTEST --coverage
test: $(target)
./run-tests# BAD: Breaks in CI
confirm:
@read -p "Are you sure? [y/N] " ans && [ "$$ans" = y ]
# GOOD: Environment variable guard
deploy: guard-CONFIRM ## Deploy (requires CONFIRM=1)
./deploy.sh
guard-%:
@if [ -z '${${*}}' ]; then \
echo "ERROR: Variable $* is not set"; \
exit 1; \
fiifdef NO_COLOR
CYAN :=
GREEN :=
RESET :=
else
CYAN := \033[36m
GREEN := \033[32m
RESET := \033[0m
endif
.PHONY: build
build:
@echo "$(CYAN)Building...$(RESET)"
$(MAKE) all
@echo "$(GREEN)Done$(RESET)"# AVOID: Incomplete dependency graph, poor -j performance
all:
$(MAKE) -C lib
$(MAKE) -C src # Can't see lib's deps!
# PREFER: Non-recursive with includes
include lib/module.mk
include src/module.mkIf recursion is necessary, always use $(MAKE) not make (preserves jobserver).
cd Bug# WRONG: Each line runs in separate shell
install:
cd /usr/local
cp myapp bin/ # Runs in original directory!
# RIGHT: Chain commands
install:
cd /usr/local && cp myapp bin/
# OR: Use .ONESHELL (changes all recipes)# BAD: CI failures are impossible to debug
build:
@$(CC) -o $@ $^
# GOOD: Verbosity toggle
build:
$(Q)$(CC) -o $@ $^
# Run: make V=1 for verbose# BAD: Bashisms without declaring bash
build:
[[ -f config ]] && source config # Fails on /bin/sh
# GOOD: Declare shell or use POSIX
SHELL := bash
# OR use POSIX: [ -f config ] && . config| Flag | Purpose |
|---|---|
make -n | Dry run (print commands, don't execute) |
make -B | Force rebuild all targets |
make -d | Debug output (why did it rebuild?) |
make --trace | Print each target as it runs |
make -p | Print database (all rules and variables) |
make -rR | Disable built-in rules and variables |
# Print variable value
$(info DEBUG: CFLAGS = $(CFLAGS))
# Warning (continues execution)
$(warning Something looks wrong)
# Error (stops execution)
$(error FATAL: Missing required variable)| Symptom | Likely Cause |
|---|---|
| "Nothing to be done" | Target exists and is up-to-date, or missing .PHONY |
| Rebuilds every time | Missing dependency, or .PHONY on file target |
Breaks with -j | Hidden dependencies between targets |
| "missing separator" | Spaces instead of tabs in recipe |
| Variable empty | Wrong expansion timing (= vs :=) or typo |
| Feature | GNU Make | BSD Make |
|---|---|---|
:= assignment | Yes | Yes |
?= assignment | Yes | Yes |
.PHONY | Yes | Yes |
$(shell ...) | Yes | != syntax |
$(wildcard ...) | Yes | No |
.DELETE_ON_ERROR | Yes | No |
Pattern rules % | Yes | Limited |
Grouped targets &: | 4.3+ | No |
SHELL is /bin/sh (often dash on Debian, not bash)SHELL := bash is declaredsed -i differs between GNU and BSDecho -e is non-portable; use printfFor Helm chart and Kubernetes Makefile patterns, consult `references/Makefile.helm-k8s` (452 lines, 47 targets). Key principles:
CHART_NAME, VERSION),derive all artifact names — eliminates hardcoding
verify-context target that checkskubectl config current-context against an allowed list; all mutating targets depend on it
KUBECTL_EXTERNAL_DIFF in Makefiles — users have their own diff viewersReference files are catalogs of patterns to pick from, not templates to copy wholesale. Real-world Makefiles typically use 10-20 targets.
Makefile.gnumake-template - Modern GNU Make skeletonMakefile.go - Go project patternsMakefile.python - Python development workflowMakefile.node - Node.js with npm integrationMakefile.docker - Docker build/push patternsMakefile.helm-k8s - Helm charts & Kubernetes operationsMakefile.portable - Cross-platform POSIX compatibleci-integration.md - CI/CD usage patterns~30 seconds. Free. No account. Every finding cites a rule and a line of evidence.