0

I have the following rules in my Makefile:

%.o:        $(HFILES)

%.o:        %.c
    $(CC) $(CFLAGS) $*.c

where HFILES contains all headers of my project.

The Problem is that this does not rebuild the object files when a header changes as intended. Why does the first line not add the headers to the prerequisites of the object files?

rtrn
  • 153
  • 1
  • 5

1 Answers1

2

Because that's not how pattern rules work. The documentation for pattern rules says that when you create a pattern rule with no recipe that cancels the pattern rule (that is, deletes it).

Since your first line is creating a pattern rule with a target %.o and prerequisites $(HFILES) but no recipe, that line simply cancels a pattern rule (which doesn't exist anyway).

You can write:

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

(you shouldn't put the -c flag in your CFLAGS variable).

Be aware that, of course, this means that if ANY header file in HFILES changes, ALL .o files that use this pattern will be rebuilt.

MadScientist
  • 92,819
  • 9
  • 109
  • 136