Why don't I need to include library.cpp in the header?

c++, header, libraries

Solution

Explained briefly:

(1) Your `library.cpp` file is sent to the preprocessor.

(2) The preprocessor reads the line `#include "library.h"` and goes and finds the file `library.h`.

(3) The contents of `library.h` are literally copied into the `library.cpp` file.

(4) The `library.cpp` file is compiled and linked with the main file.

Thus, all of the "prototypes" in the header are copied into the top of the implementation file. `.cpp` files are compiled and linked. The header files themselves are not compiled -- their contents are copied into the `.cpp` files.

Problem

I have a question about libraries. When I write a library I have 2 files: `library.h` and `library.cpp`. The first one contains the prototypes of the functions and the second one contains the definitions. Well, in `library.cpp` I include `#include "library.h"`, so they are connected in one way, but what happens with the header? Why don't I have to write `#include "library.cpp"` in the header? When I use the library in the main file, I write `#include "library.h"`, which includes the prototypes, but how does the compiler know where the definitions are?

Original source