views:

888

answers:

3

Let's say I have a makefile with the rule

%.o: %.c
 gcc -Wall -Iinclude ...

I want *.o to be rebuilt whenever a header file changes. Rather than work out a list of dependencies, whenever any header file in /include changes, then all objects in the dir must be rebuilt.

I can't think of a nice way to change the rule to accomodate this, I'm open to suggestions. Bonus points if the list of headers doesn't have to be hard-coded

+1  A: 

How about something like:

includes = $(wildcard include/*.h)

%.o: %.c ${includes}
    gcc -Wall -Iinclude ...

You could also use the wildcards directly, but I tend to find I need them in more than one place.

Michael Williamson
thanks, I was making this out to be a lot more complicated than was needed
Mike
+3  A: 

If you are using a GNU compiler, the compiler can assemble a list of dependencies for you. Makefile fragment:

.depend: depend

depend: $(OBJS)
        rm -f ./.depend
        $(CC) $(CFLAGS) -MM $^>>./.depend;

include .depend

There is also the tool makedepend, but I never liked it as much as gcc -MM

dmckee
The better answer.
strager
A: 

As I posted here gcc can create dependencies and compile at the same time:

DEPS := $(OBJS:.o=.d)

-include $(DEPS)

%.o: %.c
    $(CC) $(CFLAGS) -MM -MF $(patsubst %.o,%.d,$@) -o $@ $<

The '-MF' parameter specifies a file to store the dependencies in.

The dash at the start of '-include' tells Make to continue when the .d file doesn't exist (e.g. on first compilation).

Note there seems to be a bug in gcc regarding the -o option. If you set the object filename to say obj/file_c.o then the generated file.d will still contain file.o, not obj/file_c.o.

Martin Fido