Multiple Files

Breaking programs down into multiple files enables the principle of "doing one task and doing it well" (aka the Unix philosophy).


This principle focuses on the creation of developing smaller, modular and more manageable code with well defined interfaces. Any issues local to that code should then be more easily addressed, whilst also enabling replacement/upgrade for newer versions to provide new features, and thus saving time/effort debugging problems on long/complex/unreadable code.


Modularity also allows specialisms to be utilised by more than one program (the 'why re-invent' rule) as can be seen in the STL.


Compilation times are improved by only having to compile files that have changed. Imagine if a program consisted of a single file with thousands of lines and took say 15 minutes to compile, only for you to remember a simple change and then have to recompile everything again.


The main program file has a forward declared prototype:

#include <iostream>

int multiply(int, int) ;

int main(){
	int x, y ;
	cout << "Please enter 2 numbers to multiply:" << endl ;
	cin >> x >> y ;
	cout << "The product of " << x << " x " << y << " = " << multiply(x,y) << endl ;
	return 0 ;


Implementation of the forward declared prototype in a separate file:

int multiply(int a, int b){
	return a * b ;


When compiled in an IDE, it should automatically find and compile both files for the program.


To compile from the command line, simply include the names of the files to be compiled with the desired output file name as follows:


g++ main.cpp multiply.cpp -o multiplier


*remember to add a .exe extension for windows environments.

Leave a Reply