Beefzone
Beefzone

Reputation: 3

Header Files connection

How are header files connected to the cpp files? I have a cpp file, including header files. I understand what include does, but what about the cpp file of the header file?

Let's say:

calculate.cpp:

#include table.h

What happens with table .cpp? To fully understand calculate.cpp, is table.cpp also needed to be looked at?

Upvotes: 0

Views: 147

Answers (1)

Philipp
Philipp

Reputation: 2526

You have file A.cpp which includes B.h. When you compile A.cpp the preprocessor will include everything from file B.h to the translation unit of A.cpp and the compiler create an object file from it.

The compiler doesn't care at this point about the implementation of whatever is in B.cpp. This is dealt with separately when the compiler compiles the translation unit B.cpp. The compiler trusts at this point that in the future (at link time) there will be something when calling something from B. If not, you will end up with a linker error (undefined symbols most likely).

Here you have a very good answer on what's happening: How does the compilation/linking process work?

But just to describe it in less words:

  1. Preprocessor: reads through your .cpp and included .h files (e.g. A.cpp and B.h and creates an output which the compiler then can compile. This will independently also happen for B.cpp and its includes/defines)
  2. Compiler: Takes the output from the preprocessor and creates object files. Object files contain mostly machine code and some linker information
  3. Linker: Links the object files together so when you run the program they right functions are called.

So I guess the connection you are looking for happens in the Linking stage. That's where all the pieces come together.

Upvotes: 1

Related Questions