Skip to content

Instantly share code, notes, and snippets.

@yorickvP
Created July 24, 2012 19:05
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save yorickvP/3171926 to your computer and use it in GitHub Desktop.
Save yorickvP/3171926 to your computer and use it in GitHub Desktop.
generic C/C++ project makefile template
ifdef VERBOSE
Q =
E = @true
else
Q = @
E = @echo
endif
CFILES := $(shell find src -mindepth 1 -maxdepth 4 -name "*.c")
CXXFILES := $(shell find src -mindepth 1 -maxdepth 4 -name "*.cpp")
INFILES := $(CFILES) $(CXXFILES)
OBJFILES := $(CXXFILES:src/%.cpp=%) $(CFILES:src/%.c=%)
DEPFILES := $(CXXFILES:src/%.cpp=%) $(CFILES:src/%.c=%)
OFILES := $(OBJFILES:%=obj/%.o)
BINFILE = projectname
COMMONFLAGS = -Wall -Wextra -pedantic
LDFLAGS =
ifdef DEBUG
COMMONFLAGS := $(COMMONFLAGS) -g
endif
CFLAGS = $(COMMONFLAGS) --std=c99
CXXFLAGS = $(COMMONFLAGS) --std=c++0x
DEPDIR = deps
all: $(BINFILE)
ifeq ($(MAKECMDGOALS),)
-include Makefile.dep
endif
ifneq ($(filter-out clean, $(MAKECMDGOALS)),)
-include Makefile.dep
endif
CC = gcc
CXX = g++
-include Makefile.local
.PHONY: clean all depend
.SUFFIXES:
obj/%.o: src/%.c
$(E)C-compiling $<
$(Q)if [ ! -d `dirname $@` ]; then mkdir -p `dirname $@`; fi
$(Q)$(CC) -o $@ -c $< $(CFLAGS)
obj/%.o: src/%.cpp
$(E)C++-compiling $<
$(Q)if [ ! -d `dirname $@` ]; then mkdir -p `dirname $@`; fi
$(Q)$(CXX) -o $@ -c $< $(CXXFLAGS)
Makefile.dep: $(CFILES) $(CXXFILES)
$(E)Depend
$(Q)for i in $(^); do $(CXX) $(CXXFLAGS) -MM "$${i}" -MT obj/`basename $${i%.*}`.o; done > $@
$(BINFILE): $(OFILES)
$(E)Linking $@
$(Q)$(CXX) -o $@ $(OFILES) $(LDFLAGS)
clean:
$(E)Removing files
$(Q)rm -f $(BINFILE) obj/* Makefile.dep
@liuyang1
Copy link

liuyang1 commented Sep 4, 2016

not implement header file dependency in your makefile.

@ArashPartow
Copy link

A comprehensive and easy to use C++ Makefile example can also be found here:

https://www.partow.net/programming/makefile/index.html

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