C++ Header Files
In this page:
Why Use Header Files?
Header files are used to separate declarations from implementations. They contain function declarations, class definitions, and macro definitions. This allows you to share declarations across multiple source files.
Example: Why Use Header Files?
// shape.h
class Shape {
public:
double area();
};
// shape.cpp
#include "shape.h"
double Shape::area() { return 0.0; }
Login to try C/C++/Java/PHP code in the editor
Header Guards
Header guards prevent a header file from being included multiple times in the same file. This avoids duplicate definition compiler errors.
Example: Header Guards
// shape.h
#ifndef SHAPE_H
#define SHAPE_H
class Shape {
public:
double area();
};
#endif
Login to try C/C++/Java/PHP code in the editor
System Headers vs User Headers
System headers are included using angle brackets, like . This tells the compiler to search the system directories first. Local user headers are included using double quotes, like "MyHeader.h", which tells the compiler to search your project folder first.
Example: System Headers vs User Headers
#include <iostream>
#include "myheader.h"
int main() {
std::cout << "Angle brackets vs quotes" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Declaring Classes in Headers
To organize your code, define class blueprints in a header file and implement the actual member functions in a corresponding source file.
Example: Declaring Classes in Headers
// point.h
class Point {
public:
int x, y;
double distanceFromOrigin();
};
// point.cpp
#include "point.h"
#include <cmath>
double Point::distanceFromOrigin() {
return std::sqrt(x * x + y * y);
}
Login to try C/C++/Java/PHP code in the editor
Inline Functions in Headers
If you define a function directly inside a header, declare it as inline. This tells the linker to allow multiple definitions of the function across different source files without causing conflict errors.
Example: Inline Functions in Headers
// mathutils.h
inline int square(int x) {
return x * x; // "inline" avoids duplicate-definition linker errors
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 17 topics to unlock
0/17 topics done
Complete these topics first:
- C++ vs C Differences
- C++ Interview Questions
- C++ Debugging Techniques
- C++ Input Validation
- C++ Namespaces
- C++ Header Files
- C++ Multi-file Programming
- C++ static_cast
- C++ dynamic_cast
- C++ const_cast
- C++ reinterpret_cast
- C++ Threads (std::thread)
- C++ Mutex & Locks
- C++ async & future
- C++ Mini Project — Calculator
- C++ Mini Project — Student Management
- C++ Interview Questions Advanced