A lot of the examples I see regarding make files are somewhat inconsistent in regards to what files are considered dependencies of main.o
and I was wondering what is the safest and most efficient way of going about creating a makefile.
An example from https://www.tutorialspoint.com/makefile/makefile_quick_guide.htm:
hello: main.o factorial.o hello.o
$(CC) main.o factorial.o hello.o -o hello
main.o: main.cpp functions.h
$(CC) -c main.cpp
factorial.o: factorial.cpp functions.h
$(CC) -c factorial.cpp
hello.o: hello.cpp functions.h
$(CC) -c hello.cpp
As you can see, the header file functions.h
is a dependency of main.o
.
An example from my textbook:
myprog.exe : main.o threeintsfcts.o
g++ main.o threeintsfcts.o -o myprog.exe
main.o : main.cpp threeintsfcts.cpp threeintsfcts.h
g++ -Wall -c main.cpp
threeintsfcts.o : threeintsfcts.cpp threeintsfcts.h
g++ -Wall -c threeintsfcts.cpp
clean :
rm *.o myprog.exe
As you can see, the header file .h
and it's .cpp
are dependencies of main.o
.
I've also seen another example (from https://www.youtube.com/watch?v=_r7i5X0rXJk) where the only dependency of main.o
is main.cpp
.
Something like:
myprog.exe : main.o threeintsfcts.o
g++ main.o threeintsfcts.o -o myprog.exe
main.o : main.cpp
g++ -Wall -c main.cpp
threeintsfcts.o : threeintsfcts.cpp threeintsfcts.h
g++ -Wall -c threeintsfcts.cpp
clean :
rm *.o myprog.exe
When a main.cpp
includes a .h
file, should both the .h
and its respective .cpp
be included as dependencies?
One of the thoughts that came into my head was this: why should any .h
file be included as a dependency anyways? Wouldn't a change in any .h
file register as a change in the respective .cpp
file since the contents of the .h
are just going to be copy and pasted into the respective .cpp
file through #include?
I am also unsure of whether to have the respective .cpp
as a dependency.
(ex. main.o : main.cpp threeintsfcts.cpp threeintsfcts.h
).
I think doing so would go against one of the main benefits of makefiles which is the efficiency of modular compilation. (You would have to recompile the main
whenever threeintsfcts.cpp
changes).
However, it might make sense to do so in case threeintsfcts.cpp
changes the name of one of its functions used in main
and you forget to change it in main
.