Run default target
make
Run specific target
make build
Run multiple targets
make clean build test
Show available targets
make help
Basic Makefile structure
CC=gcc
CFLAGS=-Wall -O2
all: program
program: main.o utils.o
$(CC) $(CFLAGS) -o program main.o utils.o
main.o: main.c
$(CC) $(CFLAGS) -c main.c
utils.o: utils.c
$(CC) $(CFLAGS) -c utils.c
clean:
rm -f *.o program
.PHONY: all clean
Common patterns
SRC_DIR=src
BUILD_DIR=build
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c
mkdir -p $(BUILD_DIR)
$(CC) -c $< -o $@
Node.js Makefile
.PHONY: install build test clean
install:
npm install
build:
npm run build
test:
npm test
clean:
rm -rf node_modules dist
dev:
npm run dev
deploy: build
./deploy.sh
Docker Makefile
IMAGE_NAME=myapp
TAG=latest
.PHONY: build run stop clean
build:
docker build -t $(IMAGE_NAME):$(TAG) .
run:
docker run -d -p 8080:80 $(IMAGE_NAME):$(TAG)
stop:
docker stop $$(docker ps -q --filter ancestor=$(IMAGE_NAME):$(TAG))
clean:
docker rmi $(IMAGE_NAME):$(TAG)
logs:
docker logs -f $$(docker ps -q --filter ancestor=$(IMAGE_NAME):$(TAG))
Conditional logic
ifeq ($(ENV),production)
CFLAGS=-O2
else
CFLAGS=-g
endif
Include other Makefiles
include config.mk
Silent mode
make -s
Dry run (show commands)
make -n
Force rebuild
make -B
Parallel execution
make -j4
Help target pattern
.PHONY: help
help:
@grep -E '^[a-zA-Z_-]+:.*?
sort | \
awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
build: ## Build the project
npm run build
test: ## Run tests
npm test