Header Files vs .cpp Files in C++
What belongs in a .h header file and what belongs in a .cpp implementation file, and why the split matters.
Each .cpp file is compiled on its own, so definitions from one .cpp file are not automatically visible in another one. To share classes, functions, or global variables between files, programmers usually put their declarations in a header file and include that header in every .cpp file that needs them. The header shows what exists and how it can be used, while the .cpp file contains the actual code that makes it work. This lets different parts of the program use the same class or function without needing to see its full implementation.
Header file (.h) — shows what exists: It usually contains class declarations, function declarations, constants, type aliases, and other things that other files may need to know about. Templates are also usually placed in header files.
Implementation file (.cpp) — contains how it works: It usually contains the actual code for functions and methods, helper functions used only inside that file, and definitions of static data members.
// counter.h
#pragma once
class Counter {
public:
Counter();
void increment();
int value() const;
private:
int count_;
};
// counter.cpp
#include "counter.h"
Counter::Counter() : count_(0) {}
void Counter::increment() { ++count_; }
int Counter::value() const { return count_; }
Any file that wants to use Counter includes counter.h. The actual code is written in counter.cpp, which is compiled separately. If the implementation of Counter changes, usually only counter.cpp needs to be recompiled. Other files usually do not need recompilation unless the header file also changes.
This helps make large projects easier to build and maintain, because programmers can change the internal code without changing the shared interface.
#pragma once at the very top of a new header file. It is the simplest way to prevent accidental double inclusion.