← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 6 of 17

C++ Header Files

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?

cpp
// shape.h
class Shape {
public:
	double area();
};

// shape.cpp
#include "shape.h"
double Shape::area() { return 0.0; }

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

cpp
// shape.h
#ifndef SHAPE_H
#define SHAPE_H

class Shape {
public:
	double area();
};

#endif

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

cpp
#include <iostream>
#include "myheader.h"

int main() {
	std::cout << "Angle brackets vs quotes" << std::endl;
	return 0;
}

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

cpp
// 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);
}

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

cpp
// mathutils.h
inline int square(int x) {
	return x * x; // "inline" avoids duplicate-definition linker errors
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.