Skip to content

Instantly share code, notes, and snippets.

@davidhalter
Created April 29, 2012 20:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhalter/2552967 to your computer and use it in GitHub Desktop.
Save davidhalter/2552967 to your computer and use it in GitHub Desktop.
Makefile. No filenames needed.
# -------------------------------------------------------
# Makefile to build whatever you want.
# It tries to find all the sources you have and builds
# dependencies, to detect header file changes.
# This is especially helpful for C/C++ beginners,
# who don't want to edit a Makefile.
# https://gist.github.com/2552967
# Written by David Halter <davidhalter88@gmail.com>
# -------------------------------------------------------
CC=g++
CFLAGS=-c -O2 -Wall
SRC_DIR = src/
BUILD_DIR = build/
LDFLAGS=
SOURCES=$(wildcard $(SRC_DIR)*.cc $(SRC_DIR)*.c $(SRC_DIR)*.cpp)
# oh, how I hate make files!
HEADER_FILES_old1=$(patsubst %.cc, %.h, $(SOURCES))
HEADER_FILES_old2=$(patsubst %.cpp, %.h, $(HEADER_FILES_old1))
HEADER_FILES=$(patsubst %.c, %.h, $(HEADER_FILES_old2))
OBJECTS=$(patsubst $(SRC_DIR)%.h,$(BUILD_DIR)%.o,$(HEADER_FILES))
EXECUTABLE=main
DEPENDENCIES=$(patsubst %.o, %.d, $(OBJECTS))
all: $(SOURCES) $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CC) $(OBJECTS) $(LDFLAGS) -o $(BUILD_DIR)$@
# The -MP adds a 'phony' target for all prerequisite headers
# to stop 'make' complaining if you remove a header
# MMD generate dependency files
# The odd-looking 'sed' line makes the .d file itself
# depend on relevant source and headers
$(BUILD_DIR)%.o: $(SRC_DIR)%.*
$(CC) -MMD -MP $(CFLAGS) $< -o $@
@sed -i -e '1s,\($*\)\.o[ :]*,\1.o $(BUILD_DIR)$*.d: ,' $(BUILD_DIR)$*.d
# The include stops 'make' complaining if any .d files
# are not found (eg. on initial build).
-include $(DEPENDENCIES)
clean:
rm $(BUILD_DIR)*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment