Make your own free website on

If you have been writing makefiles for some time now and do not know how to
generate header file dependencies automatically, then I am sure, you must have
wanted to do it one time or another! Well, here is how that can be done.

Its not just a makefile magic, its a combined magic of gcc and makefile. I am
not sure at this moment if other compilers have this feature. GCC can be told
to generate header file dependency list in a way that 'make' can understand.

Say, you have a C program (a.c) that looks like this -

#include <stdio.h>
#include "a.h"

int main(){
        return 0;

Then running gcc -M a.c generates the following output

a.o: a.c /usr/include/stdio.h /usr/include/features.h \
  /usr/include/sys/cdefs.h /usr/include/gnu/stubs.h \
  /usr/lib/gcc-lib/i386-redhat-linux/3.2/include/stddef.h \

  /usr/include/bits/types.h /usr/include/bits/pthreadtypes.h \
  /usr/include/bits/sched.h /usr/include/libio.h /usr/include/_G_config.h \
  /usr/include/wchar.h /usr/include/bits/wchar.h /usr/include/gconv.h \
  /usr/lib/gcc-lib/i386-redhat-linux/3.2/include/stdarg.h \
  /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h a.h

Here is a sample makefile uses the above mentioned dependency generation technique.

SRC= a.c
OBJ= $(SRC:%.c=%.o)
DEP= $(SRC:%.c=%.d)

a.o: a.c
        echo $(OBJ)
        gcc -c a.c

        gcc -M $< > $@

-include $(DEP)