As I've learnt more C++ with time, I've looked for a use for multiple .cpp
files in one solution. This has been to no avail.
From what I can tell, multiple .cpp files just add more complexities when it comes to making sure there are no duplicates of integers or whatever, and all the idea is used for is just to sort an application a bit better. Is that the only use of doing this?
As a beginner even I thought that multiple files made it difficult for me to understand the code. But after working on a few projects I realized the importance of this modularity approach. There are many reasons for having multiple files in the project. Here I list some of them.
Let's say you are in company and you want to distribute task between many employees. Now if you as them to work on a single file then it will get difficult to keep track of who is editing what. So, we break down the task in smaller tasks where each task can be done by an individual. We provide him with a particular interface. In the case of C++, we can provide a header file with public methods and public variable. So now this individual knows what methods he can use from the part that his coworkers are working on.
So, in this situation, multiple files serve the following functions:
About complexity, actually distributing code in different files reduce code complexity.
Consider that you are working on a solo project. Let's say it has some database, functionality, input-output, GUI, some calculations like searching, etc. Now consider if you include all this thing in 1 file then it will become difficult to keep track of various thing in no time as project size increases where fast without even creator realizing. This will lead to duplicate names of functions, variables, structures, etc. Now instead of having functions
log
in each file which logs the status of the database, input-output, etc of its respective file, you will have one file withdatabaseLog
,inputLog
, etc. And what's the guarantee that you will not have some other functionality in GUI for whichinputLog
will not be the suitable title.Let's say you have some error or crashes in a project that it is easier to look at one file as there are fewer things to look at. While in one file you will have a difficult task in keeping track of what belongs to what functionality. So, Debugging gets simplified.
So, in short, you can say that if file names are assigned according to their purpose than multiple line code reduces code complexity rather than increasing it.
If you are trying to read someone else's code with multiple files then here are some tips,
And when you are working on the project make sure that each file has its own purpose, it is modular and functions do one thing. Make sure files are in a proper hierarchy according to their purpose. Also, it will be easier for you to try and implement these practices in future if use them daily. Good luck.
Hope it helps.