How does header files links with other files?

1
2
3
4
5
6
7
8
// in myclass.h

class MyClass
{
public:
  void foo();
  int bar;
};


1
2
3
4
5
6
// in myclass.cpp
#include "myclass.h"

void MyClass::foo()
{
}


1
2
3
4
5
6
7
8
//in main.cpp
#include "myclass.h"  // defines MyClass

int main()
{
  MyClass a; // no longer produces an error, because MyClass is defined
  return 0;
}


I copied all those codes from an article in cPlusPlus, and i did successfully compile them, but i still feel a little bit confuse with the process...

In the myclass.h files, it contain prototype only, and Myclass.cpp contain the function body, and it can read the Myclass.h through the #include.

Is that right?

But how does main.cpp know the function body when myclass.h contains only prototype?
I think when you compile the main.cpp, the compiler will do some check and load work to add the MyClass files to main.cpp
myclass.cpp read myclass.h

main.cpp read myclass.h

I just wonder if the file being read will also be read by the file which read it...but this doesn't sound logic, and i end out get confused. Maybe your deduction are right.
there're two processes involved: the compiler and the linker.

roughly:
the compiler is interested in the proper declaration of a symbol (size and for structures offset)
the linker resolves the symbols determined by the compiler so that the program may run

if you remove 'myclass.cpp' from your project the compiler doesn't care since he has all the informations he needs form 'myclass.h'. But the linker will complain about an 'unresolved external'
how does main.cpp know the function body

Short answer - it doesn't.

As far as the compiler is concerned, when compiling main.cpp it knows about the prototype of the function. It doesn't know anything about the function body at all.

That's the job of the linker. The linker is a separate program which runs after the compiler. Its job is to join everything together into a complete program. The input to the linker includes the object code previously generated from the two .cpp files, as well as the standard libraries as required.

A diagram to show an overview of the build process:
http://i47.tinypic.com/30cq82s.png
Oh 'linker' i see it in the compiler option, i think i get it now, thanks guys.
Topic archived. No new replies allowed.