Skip to content

Instantly share code, notes, and snippets.

@jakebesworth
Last active August 2, 2017 04:06
Show Gist options
  • Save jakebesworth/abf68fc8058bc0821a11e36a27441920 to your computer and use it in GitHub Desktop.
Save jakebesworth/abf68fc8058bc0821a11e36a27441920 to your computer and use it in GitHub Desktop.
Simple Dynamic C Makefile
# Simple Makefile
# Author: Jake Besworth (you can remove this line)
# Binary File
OBJ := myprogram.exe
# Source Files
SRC_DIR := src/
SOURCE_FILES := $(wildcard $(SRC_DIR)*.c)
# Object Files
OBJ_DIR := bin/
OBJECT_FILES := $(patsubst $(SRC_DIR)%.c,$(OBJ_DIR)%.o,$(SOURCE_FILES))
# Header Files
HEADER_DIR := include/
INCLUDE := -I$(HEADER_DIR)
# Depend Files
DEPEND_DIR := depend/
DEPEND_FILES := $(patsubst $(SRC_DIR)%.c,$(DEPEND_DIR)%.d,$(SOURCE_FILES))
# Compiler
CC := gcc
# C Compiler Flags
STD := -std=c11
# development (3), and production (0)
DEBUG := -g3
# Optimizations (Not included by default, for simplicity, but definitely recomended)
# OPT := -O2 -flto
# Dependency Flags
DFLAGS := -MMD -MF
CFLAGS += -Werror -Wall -Wextra -Wpedantic $(DEBUG)
.PHONY: all
all: $(OBJ)
$(OBJ): $(OBJECT_FILES)
$(CC) $(DEBUG) $(STD) $(OBJECT_FILES) -o $(OBJ)
$(OBJ_DIR)%.o: $(SRC_DIR)%.c
$(CC) -c $< $(CFLAGS) $(STD) $(INCLUDE) $(DFLAGS) $(patsubst $(OBJ_DIR)%.o,$(DEPEND_DIR)%.d,$@) -o $@
-include $(DEPEND_FILES)
.PHONY: valgrind clean
clean:
rm -f $(OBJ_DIR)*.o
rm -f $(DEPEND_DIR)*.d
rm -f $(OBJ)
valgrind: all
valgrind --show-leak-kinds=all --leak-check=yes --track-origins=yes ./$(OBJ)
@jakebesworth
Copy link
Author

jakebesworth commented Mar 25, 2017

Generic Makefile for building dynamic C programs. If you edit a .h file, Make will rebuild only the C-related, object files that include that header. Similarly, make will only rebuild object files and the binary with the minimal amount of recompiling. Simple valgrind example and "clean" as well.

Add to .gitignore:

*.o
*.d
<OBJ>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment