0

Assume that a1.c and a2.c include a.h which itself, in turn, includes b.h. So a1.c and a2.c are dependent on b.h indirectly.

Now I'd like the makefile to compile both of the .c files if b.h gets modified. One way is adding b.h to the dependency list of each rule along with a.h. But I feel this may make things somewhat complicated when the project grows bigger and more complex. Another way may be adding a rule for touching a.h whenever b.h changes. (I haven't tried the latter)

What is the best way to deal with nested dependencies in a makefile?

What I mean by the "best way":

  1. the makefile is as compact and simple as possible

  2. each .c file gets compiled only when at least one of its related .h files change

  3. doesn't depend on the capabilities or tools of a specific compiler or OS

apadana
  • 574
  • 2
  • 19
  • 1
    3. Automatically generate dependency information from the compiler and include it in the Makefile. – melpomene May 08 '19 at 09:16
  • Possible duplicate of [Makefile (Auto-Dependency Generation)](https://stackoverflow.com/questions/8025766/makefile-auto-dependency-generation) – Mike Kinghan May 08 '19 at 09:34
  • (Or you could step into the 21th century and start using an IDE with automatic project management, then focus on programming instead...) – Lundin May 08 '19 at 09:40
  • @MikeKinghan, that question is more about the abilities of GCC. I haven't mentioned any particular compiler. – apadana May 08 '19 at 09:52
  • 1
    In that case you will need to specify your compiler as the only way in which Make can discover all the header dependencies of your source files unless you code them manually (which is impractical) is to exploit the auto-dependency generation capabiliity of the compiler. – Mike Kinghan May 08 '19 at 09:58
  • 1
    @Lundin, makefiles are still very common, although powered by tools like GNU Autotools. – apadana May 08 '19 at 10:00

1 Answers1

2

gcc -MM *.c would output the dependencies as required.

a1.o: a1.c a.h b.h
a2.o: a2.c a.h b.h

This in turn can be used as is, as built-in rules (specifying CC and CFLAGS macros).

To avoid manually re-generating the makefile after each change, consider using CMake, and/or an IDE.

Yuri Feldman
  • 2,354
  • 1
  • 20
  • 23
  • Good. But what if I'm not using GCC? My question is more about the makefile system's own capacities. – apadana May 08 '19 at 09:54
  • 1
    @Arham Make is not a C language processor in any sense. It has no ability to parse C source files as the C preprocessor does, which it would have to do to discover the header file dependencies of a C source file. – Mike Kinghan May 08 '19 at 10:15
  • 1
    Put another way, make is a tool that can take any kind of "source" file, check its timestamp against a "target" file, and run some command (the "recipe") if they are out of date. That's it, that's all it does. It's completely generic and has no special capabilities to parse any type of source code. – MadScientist May 08 '19 at 20:56