#----------------------------------------------------------------------------------------- #A good makefile, by Pierre Chatelier and Jerome Cornet, Copyright 2006 #this Makefile understands and #put the program name to build there PROGRAM = foobarwiz #just tell the source files. If you happen to use .cpp, .m, .mm, .hh..., then #you will have to change the occurences of the tokens <%.c> and <%.h> in this file SRCS = main.c \ foo.c \ bar.c \ sub/wiz.c #you may define a file to use precompiled headers SRCSPRECOMP = precompile.h #define the compiler and the linker CC=gcc LD=$(CC) #to keep this file simple, we deliberately did not use CFLAGS, CPPFLAGS, LDFLAGS... #feel free to add and use them in this file #that's all #----------------------------------------------------------------------------------------- #everything below is automagic : dependencies, compilation... usually you do not modify it #note that we force a dependency with the Makefile. We think that if you modify the Makefile, #everything should be recompiled #dependencies are created in a sub-directory .deps/$(PROGRAM) #object files are created in a sub-directory .objs/$(PROGRAM) DEPSDIR = .deps/$(PROGRAM) OBJSDIR = .objs/$(PROGRAM) DEPS = $(SRCS:%.c=$(DEPSDIR)/%.d) OBJS = $(SRCS:%.c=$(OBJSDIR)/%.o) DEPSPRECOMP = $(SRCSPRECOMP:%.h=$(DEPSDIR)/%.d) OBJSPRECOMP = $(SRCSPRECOMP:%.h=%.h.gch) CURRENTMAKEFILE=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) #linkage $(PROGRAM): $(DEPSPRECOMP) $(DEPS) $(OBJSPRECOMP) $(OBJS) $(LD) -o $@ $(OBJS) #cleaning .PHONY: clean clean: -rm -rf $(DEPSPRECOMP) $(DEPSDIR) $(OBJSPRECOMP) $(OBJSDIR) $(PROGRAM) #creating the dependencies of the %.c files $(DEPSDIR)/%.d: %.c $(CURRENTMAKEFILE) @echo "Making dependencies for $<" @dirname $@ | xargs mkdir -p 2>/dev/null || echo "$@ already exists" >/dev/null @$(CC) -MM $< 2>/dev/null | sed 's#.*:# $@ :#1' > $@ #creating the dependencies of the %.h files, for the precompiled header $(DEPSDIR)/%.d: %.h $(CURRENTMAKEFILE) @echo "Making dependencies for precompiled header $<" @dirname $@ | xargs mkdir -p 2>/dev/null || echo "$@ already exists" >/dev/null @$(CC) -MM $< 2>/dev/null | sed 's#.*:# $@ :#1' > $@ #compiling the precompiled header %.h.gch:%.h $(DEPSPRECOMP) $(CURRENTMAKEFILE) @echo "Precompiling header $@..." @$(CC) -o $@ -c $< || echo "error. Disabling precompiled header" @echo "...Done" #compiling source files $(OBJSDIR)/%.o: %.c $(DEPSDIR)/%.d $(CURRENTMAKEFILE) @dirname $@ | xargs mkdir -p 2>/dev/null || echo "$@ already exists" >/dev/null $(CC) $(SRCSPRECOMP:%.h=-include %.h) -c $< -o $@ #include the dependencies, (if we are not actually performing a mere ) ifneq ($(strip $(MAKECMDGOALS)),clean) ifneq ($(strip $(DEPSPRECOMP)),) -include $(DEPSPRECOMP) endif ifneq ($(strip $(DEPS)),) -include $(DEPS) endif endif