Tony Tannous
Tony Tannous

Reputation: 14856

Makefile, better understanding rules

Reading the official documentation

A prerequisite is a file that is used as input to create the target. A target often depends on several files.

If my source file already includes the header, should I list the header in the rule?

src.c

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

int main()
{
    printMessage();
    return 0;
}

myheader.h

void printMessage()
{
    printf("a message to screen\n");
}

makefile

src : src.o
    cc -o src src.o

src.o : src.c
    cc -c src.c

If I add myheader.h in the prerequisite it changes nothing, the same message is printed to screen. If a header is explicitly included, should it appear in the prerequisite?

Upvotes: 1

Views: 93

Answers (2)

dbush
dbush

Reputation: 223689

The header file should be included in the dependency list.

The first time you use make to build your program, it will compile just the same whether you include myheader.h as a dependency or not. The difference is what happens when one of the files changes.

If you run make again without changing anything, it will say that "src" is up to date and won't compile anything. However, if you were to modify myheader.h and you didn't include it as a dependency, then make will say that the target is up to date. It doesn't look at the source file to see what files it includes. The make utility doesn't know anything about C or C++ source code (or any other source code). It looks only at whether the given files have changes without looking at their content.

When you include myheader.h as a dependency, if you later modify that file then running make will rebuild the program.

If you want to know all the non-system header files that a given source file depends on, you can run gcc with the -MM option. This will output a make rule listing the header dependencies of a source file.

For example, if you run gcc -MM src.c, you'll get the following output:

src.o: src.c myheader.h

You can then include that in your makefile.

Upvotes: 3

Yes, you should.

The make program uses the list of files to figure out if a dependency changed and the the target should be rebuilt as a result. It needs you to specify that dependency explicitly.

It does not see the inclusion, it only sees the rules you specified. So there is a theoretical possibility that you change the header in a way that may require a re-compilation of src.o, but make will not know you did that unless you tell it to watch out.

Upvotes: 2

Related Questions