aaaidan
aaaidan

Reputation: 7326

make: substitution references on a variable more than once?

In my makefile, the 'clean' target is removing .c.bak files by using substitution references in the SRC variable:

rm -f $(SRC:.c=.c.bak)

This causes it to delete everything in the SRC var that doesn't end in .c.

Is there an elegant way to do more than one substitution on a variable? I would, for example, like to also attempt to substitute .cpp with .cpp.bak...

Upvotes: 1

Views: 1757

Answers (1)

John Marshall
John Marshall

Reputation: 7005

If backups might appear for all the source files, not just the .c and .cpp files, you could change the substitution accordingly:

rm -f $(SRC:=.bak)

Or if you are using GNU Make, you could use its text processing functions to spell out exactly which files in $(SRC) you want to affect:

rm -f $(addsuffix .bak, $(filter %.c %.cpp,$(SRC)))

A more classical approach would be to look at how you construct the value for your $(SRC) variable. If it's an explicit list of filenames (as IMHO it should be) then you can build it up from intermediate variables for the different kinds of source file:

SRC_C = foo.c bar.c
SRC_CXX = baz.cpp apple.cpp
SRC = Makefile banana.pl carrot.pl $(SRC_C) $(SRC_CXX)

Now you can write your original substitution correctly and portably (i.e., without requiring GNU Make facilities):

rm -f $(SRC_C:.c=.c.bak) $(SRC_CXX:.cpp=.cpp.bak)

Upvotes: 4

Related Questions