Example Makefile:
MAIN=$(sh egrep -l '\<main\>.*\(' *.c)
CFILES=$(filter-out $(MAIN), $(sh ls *.c))
OBJS=$(MAIN:.c=.o) $(CFILES:.c=.o)
EXEC=$(MAIN:.c=)
CC=gcc
CFLAGS=-g -O2
LDFLAGS=
LDLIBS=
DEFAULT: $(EXEC)
$(EXEC) : $(OBJS)
$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)
- The variable
MAINis populated with egrep searching for a file that contains the stringmain(not the most stable algorithm...) CFILESare all other files with the file extension .c.OBJSare all C-files (fromMAINandCFILES) with the extension .c replaced with .o.EXECwill become the name of the executable. You can change this according to your preference.- Conventional variables used by the standard rules:
CCis the name of the C compiler,CFLAGSare given for compiling,LDFLAGSare given for linking andLDLIBSare libraries that need to be linked. - The first rule is the default when
makeis invoked without parameters. To avoid confusion and accidental overwriting, a strikingDEFAULT-target is used that just tellsmaketo build the executable. - The only rule is given to link the executable
EXECfrom all object files. - For the object files, we don't need to give a rule because
makehas standard rules for such common tasks. - The variables
CC,CFLAGS,LDFLAGS, andLDLIBSare also used by built-in rules from GNU make (gmake) that can be analyzed bymake -p.