Many times I saw people define their classes and function prototypes in the .h file, and then implement them in the .cpp file, but never #include the .cpp file. How can that link normally? Does the linker somehow "automagically" find and include the .cpp file, or am I missing the .cpp include somewhere?
Each cpp file is examined by the preprocessor. If it finds any #include somefile , the complete contents of the file somefile is copied into the cpp file at that point.
Then, the compiler takes each cpp file (which now has the contents of various header files written into it, just as if you had cut and paste it there yourself with your text editor) and compiles it into a binary object file.
When all the cpp files have been compiled into binary object files, the linker gets to work. All those object files are linked together. If you're making a library, that's pretty much it. If you're making an executable, the linker links them together with some system specific objects and presents the output executable (the system specific bits take care of setting things up when you run the executable, and there will be something in there that calls your main function).
How does the compiler know which cpp files to compile? Because the compiler is a command-line tool, and when you call it, you call it with the names of the files to compile:
g++ file1.cpp file2.cpp file3.cpp
If you're using an IDE, it may hide this from you. It's still doing it.
How does the linker know which object files to link? Because the linker is a command-line tool, and when you call it, you tell it which object files to link, much like the compiler. Again, if you're using an IDE, it may hide this from you. It's still doing it.
Attention keen kids; yes, this is simplified. Anyone who wants to know more now knows enough to go digging on google :)
Yes, the NameOfHeader.cpp has NameOfHeader.h included, but main.cpp has only NameOfHeader.h included, not NameOfHeader.cpp! Moschops, how do IDEsknow what to put in the command line, except for the main program?
Yes it does, after compiling .cpps to .objs (main.cpp generated main.obj, foo.cpp foo.obj etc.) we(IDE if you use one) pass(es) objs(main.obj foo.obj) to linker which then links them all to .exe/.dll
It shouldn't link properly because the linker doesn't know where the implementations are!
Of course it does. You told it which cpp files to compile, and this provides a list of which object files to link together. If you're using an IDE, this is probably known as a "project" or some such. It must know, otherwise you'd get a linker error ("undefined reference").