make: Variables Simplify
1
1 2.4 Variables Make Makefiles Simpler
1 ====================================
1
1 In our example, we had to list all the object files twice in the rule
1 for 'edit' (repeated here):
1
1 edit : main.o kbd.o command.o display.o \
1 insert.o search.o files.o utils.o
1 cc -o edit main.o kbd.o command.o display.o \
1 insert.o search.o files.o utils.o
1
1 Such duplication is error-prone; if a new object file is added to the
1 system, we might add it to one list and forget the other. We can
1 eliminate the risk and simplify the makefile by using a variable.
1 "Variables" allow a text string to be defined once and substituted in
1 multiple places later (⇒How to Use Variables Using Variables.).
1
1 It is standard practice for every makefile to have a variable named
1 'objects', 'OBJECTS', 'objs', 'OBJS', 'obj', or 'OBJ' which is a list of
1 all object file names. We would define such a variable 'objects' with a
1 line like this in the makefile:
1
1 objects = main.o kbd.o command.o display.o \
1 insert.o search.o files.o utils.o
1
1 Then, each place we want to put a list of the object file names, we can
11 substitute the variable's value by writing '$(objects)' (⇒How to
Use Variables Using Variables.).
1
1 Here is how the complete simple makefile looks when you use a
1 variable for the object files:
1
1 objects = main.o kbd.o command.o display.o \
1 insert.o search.o files.o utils.o
1
1 edit : $(objects)
1 cc -o edit $(objects)
1 main.o : main.c defs.h
1 cc -c main.c
1 kbd.o : kbd.c defs.h command.h
1 cc -c kbd.c
1 command.o : command.c defs.h command.h
1 cc -c command.c
1 display.o : display.c defs.h buffer.h
1 cc -c display.c
1 insert.o : insert.c defs.h buffer.h
1 cc -c insert.c
1 search.o : search.c defs.h buffer.h
1 cc -c search.c
1 files.o : files.c defs.h buffer.h command.h
1 cc -c files.c
1 utils.o : utils.c defs.h
1 cc -c utils.c
1 clean :
1 rm edit $(objects)
1