0

Lets say i have the following program, separated into different files and representing basic linear algebra elements in 3d space

point3D.hpp

vector3D.hpp

line3D.hpp #include vector3D.hpp

main.cpp #include "point3D.hpp" #include "line3D.hpp"

and i want to create a makefile for them, which dependencies do I have to consider?

So it is obvious that main.cpp directly depends on point3D.hpp and line3D.hpp and indirectly depends on "vector3d.hpp".

But what does that mean for compilation? Let's say I modified the file vector3D.hpp, i obviously have to recompile vector3D.cpp getting vector3D.o (not in that list).

But do I also have to recompile line3D.cpp -> line3D.o and main.cpp -> main.o then because they directly & indirectly depend on vektor3D.hpp, or is it sufficient just to link object files again to a new executable?

And if it varies from case to case, when is it necessary to recompile all dependent files & when is it sufficient to compile & relink the modified file.

And what is the best way to implement that correctly into a makefile?

I tried to learn more about linking & compiling in c++, but was not able to find one sufficient page which could answer my question.

ValentinM
  • 11
  • 2
  • The answer to your question is that if a header file which is _either_ directly _or_ indirectly included by a source file is modified, then the source file must be recompiled. It is of course possible that the changes to the header file _wouldn't_ actually require some source files to be changed, but that is very hard to know for sure and the results of not recompiling when necessary are so critical that it's not worth trying to avoid it. – MadScientist Jan 16 '23 at 18:53
  • There is a rule called [The One Definition Rule](https://en.cppreference.com/w/cpp/language/definition) which put over-simpley says _"don't define something two (or more) different ways in the same program"_. If you change a header and don't recompile all the modules that use that header file you risk breaking the above rule. If you break the above rule here's the fun part: _"... __The compiler is not required to diagnose this violation__, but the behavior of the program that violates it is undefined...."_ – Richard Critten Jan 16 '23 at 19:23
  • You need to recompile (generally) when anything in the [translation unit](https://en.wikipedia.org/wiki/Translation_unit_(programming)) changes. Translation units that have not changed need only be relinked. – Chris Dodd Jan 16 '23 at 20:15
  • *what is the best way to implement that correctly into a makefile?*: my preferred way is to just add `-MMD` to `CFLAGS` and then `-include *.d` somewhere in the bottom of the Makefile. Quick and dirty, but does the job. Make sure to add `clean: ; rm *.o *.d` rule to help with cleanup. – Chris Dodd Jan 16 '23 at 20:23

0 Answers0