I've been searching for this for three years and now my collection is complete.

GNU Make is a decent tool. But due to the fact that I commonly create only a handful of Makefiles per project and that its syntax is easy to forget (or -perhaps- hard to remember) - it often takes me an hour before I create a new generic Makefile for a project.

More often then not I end up analysing and recycling an existing one from one of my previous projects. Thus I wrote a generic Windows starter that will work on any folder that contains .c and .h files as long as you have The GNU C Compiler Suite and Make installed on your machine.

Simply add this Makefile to your folder and change the target (the default is "buddy.exe") to the name of your desired exe output file. Make sure that one .c file contains the main function and the rest will be done by the build system.

The main tricks being used are:

1. Obtaining list of all *.c files in folder...

SRCS    =   $(wildcard *.c)
2. ...using it to generate all object files.
OBJS    =   $(patsubst %.c,%.o,$(SRCS))
3. Creating dependency file named .depend by using -MM switch on gcc (i.e. fake compilation step).
$(CC) $(CFLAGS) $(SRCS) -MM >> .depend
4. Including dependency file into makefile using -include (minus means it will not complain if the file is not there i.e. on the first run).
-include .depend
5. And last but not least: redirection of stderr to NUL to prevent DEL command from complaining when there are no matching files.
del *.o 2>NUL
Here is the entire Makefile.


CC = gcc CFLAGS = -I. SRCS = $(wildcard *.c) OBJS = $(patsubst %.c,%.o,$(SRCS)) .PHONY: all clean all: depend buddy.exe depend: $(SRCS) del .depend 2>NUL $(CC) $(CFLAGS) $(SRCS) -MM >> .depend -include .depend %.o: %.c $(CC) -c -o $@ $< $(CFLAGS) buddy.exe: $(OBJS) $(CC) -o $@ $^ clean: del *.o 2>NUL del *.exe 2>NUL del .depend 2>NUL

Newer Posts Older Posts Home

Blogger Syntax Highliter