C/C++ header and implementation files: How do they work?

nickelpro picture nickelpro · Feb 10, 2012 · Viewed 21.9k times · Source

This is probably a stupid question, but I've searched for quite a while now here and on the web and couldn't come up with a clear answer (did my due diligence googling).

So I'm new to programming... My question is, how does the main function know about function definitions (implementations) in a different file?

ex. Say I have 3 files

  • main.cpp
  • myfunction.cpp
  • myfunction.hpp

//main.cpp

#include "myfunction.hpp"
int main() {
  int A = myfunction( 12 );
  ...
}

-

//myfunction.cpp

#include "myfunction.hpp"
int myfunction( int x ) {
  return x * x;
}

-

//myfunction.hpp

int myfunction( int x );

-

I get how the preprocessor includes the header code, but how do the header and main function even know the function definition exists, much less utilize it?

I apologize if this isn't clear or I'm vastly mistaken about something, new here

Answer

Ed Heal picture Ed Heal · Feb 10, 2012

The header file declares functions/classes - i.e. tells the compiler when it is compiling a .cpp file what functions/classes are available.

The .cpp file defines those functions - i.e. the compiler compiles the code and therefore produces the actual machine code to perform those actions that are declared in the corresponding .hpp file.

In your example, main.cpp includes a .hpp file. The preprocessor replaces the #include with the contents of the .hpp file. This file tells the compiler that the function myfunction is defined elsewhere and it takes one parameter (an int) and returns an int.

So when you compile main.cpp into object file (.o extension) it makes a note in that file that it requires the function myfunction. When you compile myfunction.cpp into an object file, the object file has a note in it that it has the definition for myfunction.

Then when you come to linking the two object files together into an executable, the linker ties the ends up - i.e. main.o uses myfunction as defined in myfunction.o.

I hope that helps