When dividing your code up into multiple files just what exactly should go into an .h file and what should go into a .cpp file?
The primary purpose of a header file is to propagate declarations to code files. Header files allow us to put declarations in one location and then import them wherever we need them. This can save a lot of typing in multi-file programs.
The header file contains only declarations, and is included by the . c file for the module. Put only structure type declarations, function prototypes, and global variable extern declarations, in the . h file; put the function definitions and global variable definitions and initializations in the .
A header file should be included only when a forward declaration would not do the job. The header file should be so designed that the order of header file inclusion is not important. This is achieved by making sure that x.h is the first header file in x.
Header files (.h
) are designed to provide the information that will be needed in multiple files. Things like class declarations, function prototypes, and enumerations typically go in header files. In a word, "definitions".
Code files (.cpp
) are designed to provide the implementation information that only needs to be known in one file. In general, function bodies, and internal variables that should/will never be accessed by other modules, are what belong in .cpp
files. In a word, "implementations".
The simplest question to ask yourself to determine what belongs where is "if I change this, will I have to change code in other files to make things compile again?" If the answer is "yes" it probably belongs in the header file; if the answer is "no" it probably belongs in the code file.
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