Last active
September 7, 2019 23:43
-
-
Save vberlier/321164cf1b8a27ee0ffaba8fea48d695 to your computer and use it in GitHub Desktop.
Generic Makefile for C projects. Supports multiple source directories, with out-of-source release, debug and memcheck builds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Project info | |
EXEC_NAME := main | |
SRC_DIRS := src | |
BUILD_DIR := build | |
# General config | |
CFLAGS += -std=c18 -Wall -Wextra -Wconversion -Werror | |
CPPFLAGS += $(addprefix -I,$(SRC_DIRS)) | |
LDFLAGS += | |
# Configure release, debug and memcheck builds | |
MODE ?= release | |
ifeq ($(MODE),release) | |
CFLAGS += -O3 | |
else ifeq ($(MODE),debug) | |
CFLAGS += -O1 -g -fsanitize=address -fno-omit-frame-pointer | |
LDFLAGS += -g -fsanitize=address | |
else ifeq ($(MODE),memcheck) | |
CFLAGS += -O0 -g | |
LDFLAGS += -g | |
START_PREFIX = valgrind --leak-check=yes | |
else | |
$(error Invalid MODE: $(MODE)) | |
endif | |
OUTPUT_DIR := $(BUILD_DIR)/$(MODE) | |
MAIN_EXEC := $(OUTPUT_DIR)/$(EXEC_NAME) | |
SRCS = $(shell find $(SRC_DIRS) -name "*.c") | |
OBJS = $(SRCS:%.c=$(OUTPUT_DIR)/%.o) | |
DEPS = $(OBJS:.o=.d) | |
# Rules | |
.PHONY: all start clean | |
all: $(MAIN_EXEC) | |
start: $(MAIN_EXEC) | |
$(START_PREFIX) ./$< | |
clean: | |
rm -rf $(BUILD_DIR) | |
$(MAIN_EXEC): $(OBJS) | |
$(CC) $(LDFLAGS) $^ -o $@ | |
$(OUTPUT_DIR)/%.o: %.c | |
@mkdir -p $(dir $@) | |
$(CC) $(CFLAGS) $(CPPFLAGS) -MMD -MP -c $< -o $@ | |
# Generated dependencies | |
-include $(DEPS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment