views:

4687

answers:

3
+2  Q: 

Loops in Makefile

I have a lot of assignments where I have to continually update a Makefile as I add more subsequently numbered C programs. Is there a way to do this with a loop which iterates over the values 1.1, 1.2, 1.3, etc.?

all: 1.1 1.2 1.3 1.4 1.5 1.6 1.7. 1.8 1.9

1.1: 1.1.o
    gcc -o 1.1 $(FLAGS) 1.1.o
1.1.o: 1.1.c
    gcc -c $(FLAGS) 1.1.c

1.2: 1.2.o
    gcc -o 1.2 $(FLAGS) 1.2.o
1.2.o: 1.2.c
    gcc -c $(FLAGS) 1.2.c

1.3: 1.3.o
    gcc -o 1.3 $(FLAGS) 1.3.o
1.3.o: 1.3.c
    gcc -c $(FLAGS) 1.3.c

1.4: 1.4.o
    gcc -o 1.4 $(FLAGS) 1.4.o
1.4.o: 1.4.c
    gcc -c $(FLAGS) 1.4.c

1.5: 1.5.o
    gcc -o 1.5 $(FLAGS) 1.5.o
1.5.o: 1.5.c
    gcc -c $(FLAGS) 1.5.c

1.6: 1.6.o
    gcc -o 1.6 $(FLAGS) 1.6.o
1.6.o: 1.6.c
    gcc -c $(FLAGS) 1.6.c

1.7: 1.7.o
    gcc -o 1.7 $(FLAGS) 1.7.o
1.7.o: 1.7.c
    gcc -c $(FLAGS) 1.7.c

1.8: 1.8.o
    gcc -o 1.8 $(FLAGS) 1.8.o
1.8.o: 1.8.c
    gcc -c $(FLAGS) 1.8.c

1.9: 1.9.o
    gcc -o 1.9 $(FLAGS) 1.9.o
1.9.o: 1.9.c
    gcc -c $(FLAGS) 1.9.c

clean:
    rm -f *.o
    rm -f 1.1 1.2 1.3 1.4 1.5 1.6 1.7. 1.8 1.9
A: 

Yes; you can use shell commands in a Makefile, and make itself may offer the looping you need. There are oodles of good examples all over the web; assuming from your use of gcc that you're also using GNU make, try here:

http://www.gnu.org/software/make/manual/make.html#Foreach-Function

Adam Liss
+5  A: 

You want a suffix rule, not a loop.

S.Lott
Good call -- a suffix rule will eliminate duplication of the build rules. Combined with a loop that specifies the dependencies, we've covered scalability as well!
Adam Liss
+2  A: 

Try a rule like:

OBJECTS = 1.1.o 1.2.o 1.3.o

all: $(OBJECTS)

%.o: %.c
    gcc $(FLAGS) %< -o $*

Then you just need to add the extra object to the list and all is sweet.

Implicit rules help you really minimise the copy/paste cycle in your makefile.

http://www.gnu.org/software/autoconf/manual/make/Implicit-Rules.html#Implicit-Rules

David Martin
Can you explain how this works?
titaniumdecoy