0

What happens when my program includes a header that includes another header? Say, for example, main.c includes header1.h, and header1.h includes header2.h. Should my makefile be:

main.x: main.o
    gcc -o main.x

main.o: main.c header1.h header2.h
    gcc -c main.c

OR is it unnecessary to include header2.h?

main.x: main.o
    gcc -o main.x

main.o: main.c header1.h
    gcc -c main.c

Or is it unnecessary to include any headers at all?

main.x: main.o
    gcc -o main.x

main.o: main.c
    gcc -c main.c
  • Yes. All included headers, including those included transitively. Note gcc will determine dependencies for you with the `-M` (and similar related like `-MM`) option. – Gene Nov 01 '16 at 01:41
  • @RuslanOsmanov hmmm, yea, but in this question, you see after one second what it's about, the other one you have to analyse a somewhat complex example. – Bodo Thiesen Nov 01 '16 at 01:43

2 Answers2

0

The point of listing dependencies in a Makefile is to let make know under what circumstances it needs to rebuild. If a file listed as a dependency has been modified since the target was built, the target needs to be rebuilt. So it's a good idea to list all files which are consulted in the coarse of building the target.

If you don't list an hour included file, then everything will still work -- until you edit the file you didn't tell make about, at which point you'll find that make might not bother to recompile.

rici
  • 234,347
  • 28
  • 237
  • 341
0

You would have to name every single include file as dependency, because (by design) make doesn't know anything about how C works. gcc and GNU make provide a solution for this:

main.x: main.o
    gcc -o main.x

main.o main.d: main.c
    gcc -MD -MF -MG -MP main.d -c main.c

-include main.d

The dash in front of include causes make to ignore missing .d files, -MD ... causes gcc to generate a file containing dependency rules for use in make (-MD causes the generation as a side effect of compilation, -MF names the file to write those to, -MG causes the creation of a rule that assumes, missing header files will be created and -MP creates phony targets for header files, so deleting a header file doesn't prevent further building because of missing dependencies).

Bodo Thiesen
  • 2,476
  • 18
  • 32