I understand that providing a definition in a header file allows other files to reference them and then the linker adds all the object files together and provides the definitions later.
Is this just so that we can reuse the implementation else where in other libraries?
If we didnt use header files or abused them and put all the code in them, i.e The full implementation what would happen? Would it take longer when compiling each file as the full definition would need to be compiled on a peer file basis? Would it cause issues with the linker as the would be multiple compiled versions of the same implementaion?
How does this work with templates?
Blair
Any code placed in your header file gets compiled every time a new compilation target includes that header file, so at a minimum yes, you will take longer to compile. This is not the significant problem generally though.
Lets say you have this header:
And these source files:
Now, when you compile each of these sources the compilation will succeed. However when you link your program, the linker will fail because you will have provided the function
f_header()twice.Templates are a special case since they are not actually code, but rather they provide a template for code to be generated based on different types. Though there is the appearance of duplication when multiple source files use them with the same types, the compiler is able to handle this special case for you.