What is the difference between include

What is the difference between include the header I need in a.cpp file and include it in a.h ?

When you include in a header, It creates a dependency for the compiler and slows down build times. This means if you modify the header you included, the compiler has more work to do and as a result, more files are compiled and that takes time.

If you include in just a cpp file, only the cpp file needs to be recompiled and so is faster.

2 Likes

Is there any performance hit during runtime, or is the negative impact limited to compile times? I’m only asking because I’m trying to understand things better and not because I think it’s a good idea to place the includes in the header files.

Thanks!

Hi Jason,
First, it is never a good idea to place includes in the header unless absolutely necessary. Yes, it does give an overhead in your C++ and in large projects this can significantly impact build times and actually impact development times. I remember optimising 200k lines of code for a C++ project and cut compile times from 5 minutes to 30 seconds by reorganising the headers - most of the includes were in headers instead of the C++. It took a long time but in the end, the time saved was worth it.

Plus, header files are only declarations of intent, not implementation and it is designed to enable other files to see what you have made available to them when you include.

If you start including in the header file, suddenly everything you include in there affects every file that uses that header file.

So, good practice is only include absolutely what you need there, nothing more. use forward declaration of classes for pointers (i.e. something like class AMyClass* System;) and include in the C++.

Where this really causes issues is if you have your own class you include in a header and this header is used by 5 other headers, for example, then the C++ has to be compiled for every file you include and has dependencies on it. it slows the compiler as it then needs multiple passes.

But your question is, does it affect runtime. No. It only impacts developer time. Given the cost of developers on a team, this is a premium and any saving is important. This is your choice. If you don’t mind slower compile times, do it in the headers.

2 Likes

Thank you for the reply and explanation, your real world example really helped provided context!

Thanks again!

1 Like

Privacy & Terms