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
MAIN
is populated with egrep searching for a file that contains the stringmain
(not the most stable algorithm...) CFILES
are all other files with the file extension .c.OBJS
are all C-files (fromMAIN
andCFILES
) with the extension .c replaced with .o.EXEC
will become the name of the executable. You can change this according to your preference.- Conventional variables used by the standard rules:
CC
is the name of the C compiler,CFLAGS
are given for compiling,LDFLAGS
are given for linking andLDLIBS
are libraries that need to be linked. - The first rule is the default when
make
is invoked without parameters. To avoid confusion and accidental overwriting, a strikingDEFAULT
-target is used that just tellsmake
to build the executable. - The only rule is given to link the executable
EXEC
from all object files. - For the object files, we don't need to give a rule because
make
has standard rules for such common tasks. - The variables
CC
,CFLAGS
,LDFLAGS
, andLDLIBS
are also used by built-in rules from GNU make (gmake) that can be analyzed bymake -p
.