I have three files- main.cpp, file1.cpp and headerFile.h.
file1 is-
#include<iostream> using namespace std; void function1(){ cout<<"this is function1 from file1"<<endl; } headerFile.h is-
#ifndef HEADERFILE_H_ #define HEADERFILE_H_ void function1(); #endif /* HEADERFILE_H_ */ main.cpp file is-
#include<iostream> using namespace std; #include "headerFile.h" int main(){ function1(); cout<<"this is main function from mainFile"<<endl; return 0; } Until this stage function1() is unknown to main.cpp file.
Now people say that as the compiler encounters #include "headerFile.h" in main file it simply copies the code of headerFile.h into main file,
hence the main file becomes-
#include<iostream> using namespace std; #ifndef HEADERFILE_H_ #define HEADERFILE_H_ void function1(); #endif /* HEADERFILE_H_ */ int main(){ function1(); cout<<"this is main function from mainFile"<<endl; return 0; } Now, here definition of function1() is still unknown to the compiler. How is this definition resolved ? Kindly explain.
.cppfile has been compiled, they get linked together into the final progam. This is when all the function definitions are matched up.