Question about Headers and Source Files

So just today I learned how to use multiple of my own header and source files, how to use multiple sources, etc. and made a new version of my first C++ console based game, but just separated it into multiple sources and included them in a header for practice.

My question isn't as much how to use them, but why? I know there are a lot of bigger projects that would use multiple sources obviously, or else it would get too long on main.cpp, but why are multiple headers useful in a program you are writing? Also is there any reason multiple source .cpp files are useful other than separating it?

Just asking so I can have a better understanding of it, sorry if it's a noob question or dumb, Thanks!
- Kevin
Last edited on
One reason for this is 'Divide and Conquer'. That means if you separate your project in smaller parts it is much easier to keep control of what is going on.

The next thing is reusable code. You may want to use the same code in different parts of your project. So having multiple header/sources raised the likeliness that you do not need to invent the wheel over and over again.
Each compiled unit is called a module. And modules themselves can be assembled in clever ways by a linker. For example, an overlaying linker can swap out unused code from memory on a system that doesn't support paging.

Modules are a manifestation of modular programs. And encourages the use of small pieces of code as the basis for large programs.
https://en.wikipedia.org/wiki/Modular_programming

It also allows multiple programmers to work on different parts of the same program at the same time. Remember, C evolved around the same time that programming was done on screens, rather than line printers or punched cards. It was useful to make each function fit on one screen, thus changing the culture of C programming.

These compiled modules can be archived together to form a static library, that can be used at link time with other programs.
Another important aspect is compile times. If your whole program was a single file you would have to recompile the whole program each time you made a change. If you instead split the program into multiple files only the files that has been modified, and the files that include those modified files, need to be recompiled.
Last edited on
Topic archived. No new replies allowed.