Multiple source files in one project

Hello people;

I have a quick question. When looking at projects programmed by other programmers, i sometimes notice that the project contains multiple .CPP files, each with a header file by the same name. I would like to know why this is done, how they are each used and are they all compiled. I have not only seen this in VC++ but in other packages such as Dev-C++.

Separating a program into different files has a few advantages -
1) faster build time (you don't have to rebuild the whole project when only a small part of it is changed)
2) better organization
3) re-usability
4) easier collaboration (different programmers can work on different files concurrently)

To build a project with more than one files, you would have to compile them separately, and finally link them together. IDEs usually do this for you if you add them to a project.

I could declare some extra functions say genRand(int seed) in extra.hpp, I could include that header in extra.cpp and then define that function, and then use that function (without including anything) in main.cpp

Separating headers (.h or .hpp files) from implementation (.cpp) files is especially useful to users of libraries. Sometimes programmers need to look at the header files to understand how to use a class. It's nice not to have all the implementation code cluttering up the file. It also allows you to keep your implementation secret. Traditionally, small functions are put into header files to allow the compiler to 'inline' them. If the function is small enough, the compiler will replace the function call with the code, saving the cost of a function call.

The definition of the class is included in the source file using the class so that the compiler can check that you are calling the class methods properly. That is why you need to include extra.hpp in main.cpp

Including the hpp in main tells the compiler (when compiling main) that a function named genRand() is available (implemented elsewhere). After all the cpp's are separately compiled, in the linking stage, the linker will see that main calls genRand(), but doesn't have an implementation for it, so it will search the other object files for the function, and find it in extra.o, and make calls to the function in main to refer to that. If the linker can't find the function you promised will be available, you will get a linker error.