Skip to content

Instantly share code, notes, and snippets.

@D3r3k23
Last active November 11, 2021 09:46
Show Gist options
  • Save D3r3k23/b2174dbdc8c256958bf480abc8117ab2 to your computer and use it in GitHub Desktop.
Save D3r3k23/b2174dbdc8c256958bf480abc8117ab2 to your computer and use it in GitHub Desktop.
Makefile for separate source and build directories. Compiles all .c files in src directory, places .o files in build directory, automatically tracks dependencies.
SRC_DIR := src
BUILD_DIR := build
EXE := $(BUILD_DIR)/a.out
GCC_FLAGS := -g -MMD
SRCS := $(shell find $(SRC_DIR) -name '*.c')
OBJS := $(subst $(SRC_DIR), $(BUILD_DIR), $(SRCS:.c=.o))
all : $(OBJS) $(EXE)
$(EXE) : $(OBJS) | $(BUILD_DIR)
@echo "------ Make $(EXE) ------"
rm -f $(EXE)
gcc $(GCC_FLAGS) -o $(EXE) $(OBJS)
$(BUILD_DIR)/%.o : $(SRC_DIR)/%.c | $(BUILD_DIR)
@echo "------ Make $(@) ------"
rm -f $@
gcc $(GCC_FLAGS) -c -o $@ $<
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
-include $(BUILD_DIR)/*.d
clean:
rm -rf $(BUILD_DIR)/*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment