C++ Multi-file Programming
In this page:
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
// Car.h
class Car {
public:
void drive();
};
// Car.cpp
#include "Car.h"
#include <iostream>
void Car::drive() { std::cout << "Driving" << std::endl; }
Login to try C/C++/Java/PHP code in the editor
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
// 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
}
Login to try C/C++/Java/PHP code in the editor
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
// globals.h
extern int totalCars;
// globals.cpp
int totalCars = 0;
Login to try C/C++/Java/PHP code in the editor
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
// helpers.cpp
static int computeDiscount(int price) {
return price / 10;
}
int applyDiscount(int price) {
return price - computeDiscount(price);
}
Login to try C/C++/Java/PHP code in the editor
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
// Account.h
class Account {
public:
double getBalance();
private:
double balance = 0;
};
// Account.cpp
#include "Account.h"
double Account::getBalance() { return balance; }
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