How do you use multiple .cpp files across your program?


I am making program that is getting complex,pretty fast. I heard that you can spread the code across multiple files. I don't really think its that easy as create a .cpp file and that's it.Could anybody explain,or perhaps link me to a tutorial,that explains how to do that?
You create many cpp files.

The compiler then turns each cpp file into an object file; when doing so, it must know at least the prototype of every function in that cpp file, which is where header files are commonly used.

The linker then takes each of those object files and joins them together into a single executable or library, depending on what you want to build. At this stage, the linker must be able to find the code for every function, and to do so it will look through all the object files and also any already existing libraries that you've linked against (for example, the iostream functions and objects).
I am still lost. You didnt quite explain in detail on how to create working .cpp files.
You didnt quite explain in detail on how to create working .cpp files.


A cpp file is a text file. Make a text file; bingo, it's also cpp file. It's up to you to make sure that the contents of the text file are correct C++ code.
Last edited on
Yes,but,how do you make multiple ones that are working? I know you have to code it,but how do you actually make it that it runs? That one C++ file can access another?
When the compiler turns the cpp file into an object file, if there are any function calls in it that it doesn't have the code for (because that function is in a different cpp file), it effectively leaves a note for the linker, saying something along the lines of: "here, we need to call such-and-such function, here are the parameters to pass into it".

When the linker gather together all the object files it will find these, and will then go looking through all the object files (which I remind you were each made out of a single cpp file) until it finds that function, and the linker will ensure that program execution jumps to the correct function at that point.
Topic archived. No new replies allowed.