Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between % and * in a makefile

The GNU make manual does not excel at explaining this part, I could not find the explanation or I could not infer the information elsewhere.

I realize % is a kind of wildcard, but what is the difference between % and * in the context of targets, dependencies and commands? Where can I use it and does it have the same meaning everywhere?

target: dependencies ...
    commands
like image 773
Jorge Bucaran Avatar asked Dec 11 '15 08:12

Jorge Bucaran


1 Answers

The wildcard character * is used to simply generate a list of matching files in the current directory. The pattern substitution character % is a placeholder for a file which may or may not exist at the moment.

To expand on the Wildcard pitfall example from the manual which you had already discovered,

objects = *.o

The proper way to phrase that if there no '.o' files is something like

objects := $(patsubst %.c,%.o,$(wildcard *.c))

make itself performs no wildcard expansion in this context, but of course, if you pass the literal value *.o to the shell, that's when expansion happens (if there are matches) and so this can be slightly hard to debug. make will perform wildcard expansion in the target of a rule, so you can say

foo: *.o

and have it work exactly like you intended (provided the required files are guaranteed to exist at the time this dependency is evaluated).

By contrast, you can have a rule with a pattern placeholder, which gets filled in with any matching name as make tries to find a recipe which can be used to generate a required dependency. There are built-in rules like

%.o: %.c
        $(CC) $(CCFLAGS) $^ -o $@

(approximating the real thing here) which say "given a file matching %.c, the corresponding file %.o can be generated as follows." Here, the % is a placeholder which can be replaced by anything; so if it is applied against an existing file foo.c it says how foo.o can be generated.

You could rephrase it to say * matches every matching file while % matches any matching file.

like image 180
tripleee Avatar answered Sep 18 '22 07:09

tripleee