0

Can someone please help me to understand, why for non-template classes, it is recommended to separate code in header and source file? Is that only code styling or does this approach avoid possible errors (e.g., linker errors)?

I'm wondering since in case of template classes, we are not even allowed to do the separation.

Many thanks in advance!

abraham_hilbert
  • 2,221
  • 1
  • 13
  • 30
  • 1
    Sorry for the close, missed the "non-" – Barry Nov 19 '17 at 15:05
  • Does this answer your question? [Why have header files and .cpp files?](https://stackoverflow.com/questions/333889/why-have-header-files-and-cpp-files) – ChrisMM May 01 '20 at 18:27

1 Answers1

1

Is that only code styling or does this approach avoid possible errors (e.g., linker errors)?

It's mainly used to reduce interdependencies of implementation details in the compilation phase, and such lower overall compilation times.

If you change an inlined implementation, all of the translation units seeing it need to be recompiled.

With separate declaration in header files and only referring to the function interface (signature) for non templated functions or classes, recompiling isn't needed, if the internal implementation changes.


I'm wondering since in case of template classes, we are not even allowed to do the separation.

Templates are a bit different, since type parameters are injected into the definition. These cannot be instantiated in separate translation units, unless keeping track and implementing all of the foreseeable type specializations there.

user0042
  • 7,917
  • 3
  • 24
  • 39
  • Thank you. What about error handling? Are there cases requiring to split a class in header and source files in order to avoid errors (e.g., linker errors)? – abraham_hilbert Nov 19 '17 at 14:56
  • @abraham_hilbert I don't get your concerns about linker errors? You are allowed to inline everything at any time. You just need to be aware about collisions of multiple definitions when linking. – user0042 Nov 19 '17 at 14:57