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?
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.
There is a tool called linker which is responsible for link your generated object files. You should look for compilation process to understand it better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With