Each cpp file is compiled individually. When compiled, it has literally no idea of what is inside any other files in your program. The compiler doesn't really have a concept of a program as a whole, it just has 1 source file that it compiles.
With that in mind, #include is a glorified copy/paste operation. The header you #include is effectively copied to the source file being compiled. This allows you to have common code across several different cpp files.
For example, if you try to compile MyClass.cpp
without including MyClass.h, you'll get errors because the compiler won't know what MyClass is (it is defined inside the header file)
Once each cpp file has been compiled individually, the compiler is done. It generates "object files" for each compiled source file.
From here, the
linker takes over, and effectively combines all of those object files into the final program.
So why have .h and .cpp files for MyClass? Why not just put everything in a header file?
Well that would be absolute murder for your compile time (especially for larger programs), as every time you make any modification to any file, the entire program would need to be recompiled.
By separating them into several source files -- if you make a change to any individual cpp file,
only that cpp file needs to be recompiled (and the the program re-linked). Or if you change a header file,
only cpp files that #include that header need to be recompiled.
Generally, the way this works is that struct/class bodies and function prototypes go in the header, so that #including that header allows usage of all those structs/class/functions in all cpp files that #include it. Whereas the bodies of functions go in the cpp file, as the details of how the function works does not need to be compiled into each source file -- it only needs to be in one of them.
Why do I do this? I thought you have to link the header file not MyClass.cpp |
Nope. Header files are not linked.
Nor are they compiled.
They're just copy/pasted into source files. Source files are compiled into object files, and object files are linked together to form the final binary.
EDIT:
Also, I think you're crazy for not using an IDE. The integrated debugger alone is reason enough to use one -- nevermind the fact that it makes compiling/linking trivial and does not require you to write batch files or makefiles. Or (shudder) manually evoke the compiler via commandline every time you want to build.