Skip to content

Instantly share code, notes, and snippets.

@rezan
Last active February 25, 2025 12:30
Show Gist options
  • Save rezan/63e92fcc86c8eb50ec470a568d1110f9 to your computer and use it in GitHub Desktop.
Save rezan/63e92fcc86c8eb50ec470a568d1110f9 to your computer and use it in GitHub Desktop.
Makefile with auto dependencies, source subdirs, and a build directory
# Makefile with auto dependencies, source subdirs, and a build directory
# Binary name
NAME=test
CC=gcc
CFLAGS=-g -Wall -I.
DEPFLAGS=-MMD -MP
LDFLAGS=
LIBFLAGS=
BUILD_DIR=build
SOURCE:=$(shell find * -type f -name '*.c')
OBJECTS:=$(patsubst %,$(BUILD_DIR)/%.o,$(basename $(SOURCE)))
DEPS:=$(OBJECTS:.o=.d)
BUILD_DIRS:=$(sort $(dir $(OBJECTS)))
.PHONY: all clean
all: $(NAME)
$(NAME): $(OBJECTS)
$(CC) $(LDFLAGS) -o $@ $(OBJECTS) $(LIBFLAGS)
$(BUILD_DIR)/%.o: %.c | $(BUILD_DIRS)
$(CC) $(CFLAGS) $(DEPFLAGS) -c $< -o $@
$(BUILD_DIRS):
mkdir -p $@
include $(wildcard $(DEPS))
clean:
rm -rf $(NAME) $(BUILD_DIR)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment