Friday, June 29, 2018

How do you compile and run multiple files in a C++ project?

Projects can be simple, or complex and can run into many lines. You can write your code in multiple files, compile them together and run. You basically have a main program file that will call the other files. However, you need to indicate in the main file that you will be utilizing the other files.

Let us say, you want to calculate the area of a rectangle and the volume of rectangular solid and display them in the console. You can have a code file each, for calculating area and volume. You can display the calculated values in the main program.

This is carried out using Visual Studio Community (free) 2017.

Here is the project file

Here is how add a New CPP file.


A new file area.cpp was added and coded as shown.

Another new file vol.cpp was added as shown.


The AreaVolume project file AreaVolume.cpp is as shown. It calculates the area of a rectangle 5x5 and the volume of the solid with sides 4,5 and 6.

The two following two lines in AreaVoume.cpp reference the area.cpp and vol.cpp files:

int area(int x, int y);
int vol(int x, int y, int z);

If you compile and run this program you should see this in the display:


Note that the following is included in all the files:



No comments: