26

I am playing around with makefiles and I came across %.o or %.c. From what I understood, it specify all c or o files. But why this work:

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

and this doesn't work

SOURCE := $(wildcard *.c)

$(SOURCE:.c=.o): SOURCE
        $(CC) -c $^  -o $@

Both expression specify all the files. so what %.o: symbol in make file does ?

2 Answers 2

30

The construct:

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

is a pattern rule, which is a type of implicit rule. It specifies one target and one dependency, and causes one invocation of $(CC) for each target. While this:

SOURCE := $(wildcard *.c)

$(SOURCE:.c=.o): $(SOURCE)
        $(CC) -c $^ -o $@

is a standard rule but it has (possibly) many targets and many dependencies. Yet for all of that, it will only invoke $(CC) once.

0
7

Both expression specify all the files.

Nope, the first rule tells make how to obtain an .o file given the corresponding .c file. Note the singular: a single file.

The second rule (claims to) tell make how to obtain a bunch of .o files, given another bunch of corresponding .c files. Note the plural: all .c files resulting from the *.c globbing.

On a side note, %.o: %c is a GNU extension.

On another side note, you won't be learning how to use make on StackOverflow. You should consider reading a book instead.

2
  • 15
    RTFM, really? I thought the point of stackexchange was to purge that mentality.
    – daknowles
    Apr 29, 2020 at 21:49
  • @daknowles I'd gladly purge my answer out of existence, but I can't do that wile it's still accepted. shrug Jul 1, 2021 at 11:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .