Vikrant Waje
Vikrant Waje

Reputation: 11

pattern matching rule in makefile

I am learning makefile and came across pattern match rule as follows:

%.o : %.c
        $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $

My doubt is the above rule(as per my knowledge) converts source file into object file, but with the use of automatic variable $< in above rule, it should always convert the first source file into object file, right? So suppose I have three source file name f1.c,f2.c, f3.c, the above rule should convert only f1.c into f1.o as per my assumption because of use of automatic variable $<. Correct me If I am wrong.

Upvotes: 0

Views: 551

Answers (1)

Vroomfondel
Vroomfondel

Reputation: 2898

You are only partly wrong.

%.o : %.c is a pattern rule and make executes in this case the rules only for pairs of .o and .c files which have a common prefix.

To explain this a bit more assume that make has come to consider a target ending in .o. Looking into its stored rules it finds that this exactly matches the target in the above pattern rule - it proceeds then by taking the string part that matches the % (called the stem of the target) and inserting it verbatim into all the % which appear on the (right) prerequisite side. In our case this gives e.g. a foo.o : foo.c but never a foo.o : foo.c foo1.c bar1.c because the right side really only consists of the one name which you gave in the pattern, which is %.c.

Of course you could have e.g. a %.o : %.h %.c and then $< would indeed refer to the matching .h file which would render a recipe like the above useless for compilation. It's really essential to read a bit deeper into https://www.gnu.org/software/make/manual/make.html when dealing with make because there are many more things to consider than I can mention in an SO answer.

EDIT: Sorry that I missed out on a part of your question: regarding pattern rules, or rather, all rules in make, it is always the question which is the ultimate target, i.e. the one which make encounters first (or are given on the command line). If this target depends on your files f1.o f2.o f3.o then all these intermediate targets will be made because the pattern rule matches each of them. In other words: make instantiates the pattern rule for every single target that it finds during the traversal of the dependency tree originating in your final target(s) - it is not one single rule which receives all matching targets at once but, as the name says, a pattern for how to create an actual rule for one single concrete target.

Upvotes: 2

Related Questions