When working in C/C++ programs, header files can become unmanageable when using multiple source & header files. I know that make lets you define file dependencies, such that a file is only recompiled if a dependency changes.
Let's say I have a (simplified) project that uses this structure:
I want to have a makefile that works somewhat like this:
run: exe
./exe
exe: a.h
gcc main.c -o exe
a.h: b.h
The idea behind this would be that, by making a.h depend on b.h, if either a.h or b.h change, exe is re-compiled (this can also be done by having exe depend on a.h and b.h, but doing so would be unmanageable in projects with 20+ header files with their own dependency tree)
However, when I tried doing this (with some demo source & header files), changing b.h didn't result in exe recompiling.
main.c:
#include "a.h"
int main() {
printf ("magic number is: %d\n", MAGIC_NUM);
}
a.h:
#include <stdio.h>
#include "b.h"
b.h:
int MAGIC_NUM = 42;
Even when I change the value of MAGIC_NUM, exe doesn't recompile. Is there some way of achieving this with make?
You can instead use gcc
's -MMD
flag to generate a makefile that contains header dependencies.
run: exe
./exe
exe:
gcc main.c -o exe -MMD
-include exe.d
In use:
$ make
gcc main.c -o exe -MMD
./exe
magic number is: 42
$ cat exe.d
exe: main.c a.h b.h
$ sed -i 's/42/19/' b.h
$ make
gcc main.c -o exe -MMD
./exe
magic number is: 19