What's the difference between including a header file in a header file vs including it in a implementation file?
This
Ex:
// test.h
#include"globals.h"
class Test
{
Test();
};
vs
//test.cpp
#include"globals.h"
Test::Test()
{
}
The general principle is that you want to minimise dependencies wherever reasonably possible, so:
if your interface (.h) references anything in a given header then that header needs to be #included in the interface (.h)
if you only reference a given header in your implementation (.cpp) (and not in your interface) then you should only #include that header in the implementation
you should also try to only #include headers that are actually needed, although this can be difficult to maintain during the lifetime a large project
So for your example above, if you don't reference anything from globals.h in test.h, but you do reference it in test.cpp, then the #include should go in test.cpp. If you reference anything from globals.h in test.h though then you need the #include in test.h.
If you are including some implementation specific external headers, you had better include them in cpp file to reduce header dependeny on the API file. Including third party headers in the cpp files is a good way for data hiding so that library user will not know much about your references.
It is a good practice to include headers files in just where they are needed to increase the eligibility of your code and making your project easily modifiable for future development.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With