Header File (C++)

https://www.learncpp.com/cpp-tutorial/header-files/

https://www.cs.odu.edu/~zeil/cs333/f13/Public/faq/faq-htmlsu21.html

A .h file contains shared declarations, a .cpp file contains definitions and local declarations. This is basically doing Forward Declaration.

Question

What is the point of declaring in the header file if you reuse it in the .cc file? Well if you have multiple .cc files, where one calls the functions of another file, how do you import the functions? You need the header file…

Also, .h help with more readable code, more efficient for the compiler, and is needed in cases of cyclical dependencies, see Forward Declaration (not too sure…).

Very important that you understand the difference between declarations and definitions

  • A .h file is intended to be #included from many different .cpp files that make up a single program
  • (IMPORTANT) The Preprocessor actually replaces each #include by the full contents of the included .h file. Consequently, a .h file may be processed many times during the compilation of a single program, and should contain should contain only declarations.
  • A .cpp file is intended to be compiled once for any given build of the program. So the .cpp file can have any declarations that it doesn’t need to share with other parts of the program, and it can have definitions. But the main purpose of a .cpp file is to contain definitions that must only be compiled once. The most common example of this would be function bodies.

NEVER do this

Never, ever, ever, name a .cpp file in an #include. That defeats the whole purpose of C++ program structure. .h files are #include d; .cpp are Compiled. (see compiler)

Typical program in C++ will consist of many .cpp files.