Superlimonade
Superlimonade

Reputation: 25

How is automatic dependency generation with GCC and GNU Make useful?

I found many ways online to use the -M-type flags for GCC (or G++) to automatically generate dependencies in your Makefile. All approaches seem similar, I implemented this one.

All arguments I could find in favor are along the lines of: It helps you in that you don't have to manage dependencies manually. I don't see why.

Consider the following files:

main.c

#include "foo.h"
int main() { foo(); return 0; }

foo.h

void foo();

foo.c

#include "foo.h"
void foo() { ... }

I would say that main.c depends on foo. However, when I run make main.o, foo is not built. The dependency file main.d contains (which explains why foo has not been built):

main.o: main.c foo.h

foo.h:

Now if I were to create an executable (e.g. app: ; $(CC) -o app main.c, with or without auto-dependency generation flags), I would still have to manually specify that it depends on foo.o.

So my question is: how does the auto-dependency generation save me any work if I still have to specify the dependency on foo.o?

Upvotes: 2

Views: 530

Answers (2)

raspy
raspy

Reputation: 4261

No, main.c does not depend on foo. To be more exact main.c does not depend on anything but the text editor. It's the main.o that depends on main.c and foo.h as those files are required to compile main.o. Your final binary should depend on main.o and foo.o to be linked together, but it needs to be explicitly stated - neither make nor linker will find out what files you want to build together.

What this autodependency gives you is the notation that when foo.h changes, main.o will need to be recompiled (as this is included from main.c) even though main.c itself did not have any changes.

Upvotes: 1

Beta
Beta

Reputation: 99114

"I would say that main.c depends on foo."

Not quite; main.o depends on foo.h, and app depends on foo.o.

Automatic dependency generation can take care of that first dependency; the compiler finds #include "foo.h" in main.c and takes note of it.

The second dependency you must take care of. Neither the compiler nor Make can deduce it. (Bear in mind that not every header file has a corresponding source file with a matching name.)

Upvotes: 0

Related Questions