Previous      Up      Previous     Course Home   e-mail

2.16 What goes in a .h file? What goes in a .cpp file?

The short answer is that a .h file contains shared declarations, a .cpp file contains definitions and local declarations.

It’s important that you understand the difference between declarations and definitions.

Never, ever, ever name a .cpp file in an #include. That defeats the whole purpose of a C++ program structure. .h files are #included; .cpp files are compiled.

A typical program will consist of many .cpp files.

Usually, each class or group of utility functions will have their definitions in a separate .cpp file that defines everything declared in the corresponding .h file. The .h file can then be #included by many different parts of the program that use those classes or functions, and the .cpp file can be separately compiled once, then linked together with the output of other .cpp files to form the complete program.

Splitting the program into pieces like this helps, among other things, divide the responsibility for who can change what and reduces the amount of compilation that must take place after a change to a function body.

 Previous      Up      Previous     Course Home   e-mail