#include &
Declarations vs Definitions
Master the C++ preprocessor directive that brings code together, and learn the crucial difference between declaring and defining your functions and variables.
What is #include?
Before your C++ code is compiled, a special tool called the preprocessor runs first. The #include directive tells the preprocessor: "Copy the entire contents of the specified file and paste them right here."
This is how your program gains access to library features like the output stream cout, the math function \(\text{sqrt}()\), and the string type: their declarations live in header files that you include.
Two Forms of #include
The Preprocessor Pipeline
Declarations vs Definitions
This is one of the most important distinctions in C++. A declaration tells the compiler that something exists and what its type is. A definition actually creates it: allocating memory or providing the function body.
The One Definition Rule (ODR)
C++ enforces a strict rule: every function and global variable must have exactly one definition across the entire program. Multiple definitions cause a linker error.
Functions: Declaration vs Definition
Variables: Declaration vs Definition
Declaration vs Definition: Side by Side
| Aspect | Declaration | Definition |
|---|---|---|
| Purpose | Introduces name and type | Creates the actual entity |
| Memory | No allocation | Allocates memory |
| Repetition | Many times OK | Exactly once (ODR) |
| Functions | Ends with ; | Has { body } |
| Variables | Uses extern | No extern, or has initializer |
| Where? | Header files (.h) | Source files (.cpp) |
What Goes in a Header File?
How to Organize Your Code
Example: Single File Program
In a small, single-file program, you often see both the declaration (prototype) and definition in the same file:
Example: Multi-File Project
#define MATH_H
int square(int n);
#endif
int square(int n) {
return n * n;
}
int main() {
int x = square(5);
}
Include Guards: Preventing Double Inclusion
If file A includes file B, and file C also includes file B, then any file that includes both A and C gets B's contents twice. Include guards prevent this.
#define MY_H
... declarations ...
#endif
... declarations ...
Simpler, widely supported
Example: What Goes Wrong?
Common Mistakes
Question 1 of 5
What does the #include directive do?
Question 2 of 5
Which of the following is a declaration but not a definition?
Question 3 of 5
You have two .cpp files that both include a header containing int helper() { return 42; }. What happens?
Question 4 of 5
What is the purpose of include guards (#ifndef / #define / #endif)?
Question 5 of 5
Which #include syntax should you use for your own project header file called player.h?