How does the main function know about function definitions (implementations) in a different file?
For example, say I have 3 files:
//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?
The header file declares functions/classes – i.e. tells the compiler when it is compiling a
.cppfile what functions/classes are available.The
.cppfile 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.hppfile.In your example,
main.cppincludes a.hppfile. The preprocessor replaces the#includewith the contents of the.hppfile. This file tells the compiler that the functionmyfunctionis defined elsewhere and it takes one parameter (anint) and returns anint.So when you compile
main.cppinto object file (.o extension) it makes a note in that file that it requires the functionmyfunction. When you compilemyfunction.cppinto an object file, the object file has a note in it that it has the definition formyfunction.Then when you come to linking the two object files together into an executable, the linker ties the ends up – i.e.
main.ousesmyfunctionas defined inmyfunction.o.