4.1 List of source files

We cannot just leave things as they are. There is always a better way.

The following is the next revision of the Makefile:

CFLAGS = -O -Wall -g  
SRC = main.c array.c  
 
main:  $(SRC:.c=.o)  
gcc $(CFLAGS) -o main $(SRC:.c=.o)  
 
array.o:  array.c array.h  
gcc $(CFLAGS) -c array.c  
 
main.o:  main.c array.h  
gcc $(CFLAGS) -c main.c 

Here, we added the variable CSRC, which consists of a complete list of source filenames. When we want to specify the dependency of main, we use “$(CSRC:.c=.o)”. Let’s see what this means.

$(CSRC:.c=.o)” is a substitution operator. It says take the content of CSRC, but replace all .c occurances with .o.

This technique is useful because when we want to add an full-screen user interface to this project, then we only need to add ui.c to the definition of CSRC, and add the rule to make ui.o. There is no need to update the rule that updates main anymore.