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 ?

Mero
  • 363
  • 1
  • 3
  • 6

2 Answers2

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.

Stephen Rauch
  • 4,209
  • 14
  • 22
  • 32
6

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.

Satō Katsura
  • 13,138
  • 2
  • 31
  • 48