Roman
Roman

Reputation: 131258

How does % in Makefiles work?

I am trying to understand how makefiles work. If I try the following

1.out : 1.inp
    cat 1.inp

it, works as expected (if 1.inp is newer as 1.out or if 1.out does not exist, the content of 1.inp is printed).

Then I need to do the following:

cat 1.inp
cat 2.inp
cat 3.inp

I thought that for that I can use

%.out : %.inp
    cat $<

but it does not work. Can anybody please explain to me the use of %?

Upvotes: 0

Views: 98

Answers (1)

Mike Kinghan
Mike Kinghan

Reputation: 61610

In your first makefile:

1.out: 1.inp
    cat 1.inp

1.out is a target with a prerequisite 1.inp and a command cat 1.inp. This constitutes a rule for making 1.out and if you run the makefile, specifying either no explicit target or the target 1.out, the rule will be executed.

In your second makefile:

%.out: %.inp
    cat $<

you have only expressed a pattern rule for making a target of the form something.out from a prerequisite of the form something.inp You have not specified any actual targets that the makefile can make.

You can specify 1.out as a target with a makefile like this:

%.out: %.inp
    cat $<

1.out:

In that case 1.inp will be cat-ed when 1.inp is newer that 1.out

Or you can specify a phony target, e.g. all, that has prerequisite targets 1.out, 2.out, 3.out in a makefile like this:

.PHONY: all

%.out: %.inp
    cat $<

all: 1.out 2.out 3.out

In this case each of 1.inp, 2.inp and 3.inp will be cat-ed when it is newer than the corresponding .out file.

Whenever make discovers that it has to make a target of the form something.out, it will recognize that the pattern rule is applicable and will execute the matching instance of the pattern rule.

Upvotes: 4

Related Questions