Splitting C++ code into several files
Introduction
Only small programs are convenient to keep in one file. Splitting code into several files can simplify development and speed up compilation.
Moving part of the code into a neighbouring .cpp file
A file can be split into several parts and these .cpp files put in one directory.
Let us call the main file, where you call main()
Main.cpp
Create the file
Functions.cpp
and move all the functions there.
In
Main.cpp
list the names of the functions you moved and the arguments they take.
Main.cpp
#include <iostream>
using namespace std;
double add(double x, double y);
int main() {
double b = add(1.3, 4.5);
cout << "1.3 + 4.5 is " << b;
return 0;
}
Create a new file Functions.cpp that will contain only the functions:
double add(double x, double y)
{
return x + y;
}
Header Files
To avoid listing every function you want to use in the main file you can mention them in a special header file with the .h extension
Let us call it
Functions.h
and include it in the main file with the #include directive
Main.cpp
#include <iostream>
#include "Functions.h"
using namespace std;
int main() {
double b = add(1.3, 4.5);
cout << "1.3 + 4.5 is " << b << "\n";
return 0;
}
The file Functions.h
#pragma once
double add(double x, double y);
#pragma once
or
#ifndef
#define
are needed so that the same .h file is not loaded many times. After the first inclusion all further attempts are ignored.
The file Functions.cpp stays unchanged.
Compiling and running
To compile the project you have to list all the needed .cpp files.
In this example they are
g++ -std=c++23 Main.cpp Functions.cpp -o main
./main
1.3 + 4.5 is 5.8
An example with overloading
Let us add functions of a different type to make sure the code works
If, as an experiment, you want to
overload a function
add() nothing in the approach described above has to change.
Just add the overloaded function to
Functions.cpp
and
Functions.h
and then call it from
Main.cpp
Main.cpp
#include <iostream>
#include "Functions.h"
using namespace std;
int main() {
double b = add(1.3, 4.5);
cout << "1.3 + 4.5 is " << b << "\n";
double c = add(1.0,2.0,3.0);
cout << "1 + 2 + 3 is " << c << "\n";
// 6
return 0;
}
Functions.cpp
bool test(bool x)
{
return x;
}
bool test(double x)
{
return x > 0;
}
double add(double x, double y)
{
return x + y;
}
double add(double a, double b, double c)
{
return a + b + c;
}
Functions.h
#pragma once
double add(double x, double y);
double add(double a, double b, double c);
bool test(bool x);
bool test(double x);
void test(int y);
g++ -std=c++23 Main.cpp Functions.cpp -o main
./main
1.3 + 4.5 is 5.8
1 + 2 + 3 is 6
If there are many files it is sometimes useful to create
Makefile
You can read more in the articles
The code on this page was run with g++ 15.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Andrei Olegovich