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

C++ Multi-file Programming

Introduction to Multi-file Projects

Larger C++ projects are split into multiple files to make the code easier to manage. Typically, each class or module gets its own header file (.h) for declarations and its own source file (.cpp) for implementations.

Example: Introduction to Multi-file Projects

cpp
// Car.h
class Car {
public:
	void drive();
};

// Car.cpp
#include "Car.h"
#include <iostream>
void Car::drive() { std::cout << "Driving" << std::endl; }

The Compilation Process

When you compile a multi-file project, the compiler compiles each source file (.cpp) individually into an object file (.o or .obj). The linker then combines all these object files into a single runnable program.

Example: The Compilation Process

cpp
// main.cpp
#include "Car.h"

int main() {
	Car car;
	car.drive();
	return 0;
	// each .cpp compiles to its own .o file, then the linker combines them
}

Sharing Variables with extern

To share a global variable across multiple files, use the extern keyword in your header file. This tells the compiler that the variable exists, but you must initialize it in only one source file.

Example: Sharing Variables with extern

cpp
// globals.h
extern int totalCars;

// globals.cpp
int totalCars = 0;

Static Functions for Isolation

If you want to restrict a function or global variable so it can only be used within the file where it is declared, use the static keyword. This prevents naming conflicts with other source files.

Example: Static Functions for Isolation

cpp
// helpers.cpp
static int computeDiscount(int price) {
	return price / 10;
}

int applyDiscount(int price) {
	return price - computeDiscount(price);
}

Organizing Classes Across Files

In object-oriented programming, classes should be organized neatly across files. Keep the class declaration in your header file and the member function implementations in the source file.

Example: Organizing Classes Across Files

cpp
// Account.h
class Account {
public:
	double getBalance();
private:
	double balance = 0;
};

// Account.cpp
#include "Account.h"
double Account::getBalance() { return balance; }

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.