Makefile, header dependencies

2019-01-01 14:24发布

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

10条回答
栀子花@的思念
2楼-- · 2019-01-01 15:11

Here's a two-liner:

CPPFLAGS = -MMD
-include $(OBJS:.c=.d)

This works with the default make recipe, as long as you have a list of all your object files in OBJS.

查看更多
时光乱了年华
3楼-- · 2019-01-01 15:16

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

depend: .depend

.depend: $(SRCS)
        rm -f ./.depend
        $(CC) $(CFLAGS) -MM $^ -MF  ./.depend;

include .depend

or

depend: .depend

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

include .depend

where SRCS is a variable pointing to your entire list of source files.

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

查看更多
琉璃瓶的回忆
4楼-- · 2019-01-01 15:16

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.

Note that this only works well on small projects, since it assumes that every object file depends on every header file.

查看更多
初与友歌
5楼-- · 2019-01-01 15:17

This will do the job just fine , and even handle subdirs being specified:

    $(CC) $(CFLAGS) -MD -o $@ $<

tested it with gcc 4.8.3

查看更多
登录 后发表回答