Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 387
Miguel Ruiz Avatar asked Dec 08 '22 14:12

Miguel Ruiz


2 Answers

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.

like image 131
Derek Avatar answered Jan 03 '23 02:01

Derek


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.

like image 33
dieram3 Avatar answered Jan 03 '23 03:01

dieram3