2

For example if I have A.h that includes B.h. And I have the source file A.c for A.h. Do i need to include B.h in the dependency list of every sample.c (that calls functions in A.c) while creating makefile ?

kkr
  • 61
  • 1
  • 7
  • Why don't you try without including them as dependencies and see what happens. The best way to learn, in my experience, is by trying. – Eli Sadoff Nov 02 '16 at 19:57
  • 1
    The best practice is to include *all* of the *direct* dependencies. Even if you know some of them are including each other. – Eugene Sh. Nov 02 '16 at 19:57
  • 1
    Generate such dependencies automatically. There are sample makefile which provide this. If you are not bound to make, consider a modern build tool which has this feature built-in, e.g. SCons. – too honest for this site Nov 02 '16 at 20:14

1 Answers1

1

You should include all non-system headers, direct and indirect, in the rule for a given source file.

Suppose you have the following:

b.h:

#ifndef B_H
#define B_H

struct s1 {
    int f1;
};

void f1(int p1);

#endif

a.h:

#ifndef A_H
#define A_H

#include "b.h"

void f2(struct s1 *p1);

#endif

a.c

#include "a.h"

void f3()
{
    struct s1 my_s1;
    my_s1.f1 = 1;
    my_s1.f2 = 2;
    f2(&my_s1);
}

Suppose the definition of struct s1 in b.h changes to remove the field f2. If b.h is not included in the dependency list for a.c, a.c won't be recompiled. Then you end up linking the existing object file with another with conflicting definitions for struct s1. You then end up with undefined behavior.

So you need to fugure out all dependencies. Luckily, gcc has an option to generate the dependency rules for you:

gcc -MM a.c

This will output a rule suitable for make that has all non-system include files listed, both direct and indirect.

a.o: a.c a.h b.h
dbush
  • 205,898
  • 23
  • 218
  • 273