Wendel
Wendel

Reputation: 19

Why is header including sufficient for definitions?

as far as i understood; headerfiles declare things. Now including header files like #include iostream includes the header file iostream.h. This is telling the compiler for example „there is something called: cout“. QUESTION: How does the compiler get to the definition of cout (or all the other functions)? In my understanding the compiler only gets to know names and types but no definitions.

Upvotes: 0

Views: 63

Answers (1)

Aconcagua
Aconcagua

Reputation: 25518

Actually: It doesn't. It needs to know how the objects look like, what interfaces they offer (so for std::cout that's a some std::ostream stream object, apparently a subclass of) and that such objects do exist somewhere. That's it. What the compiler then does is adding placeholders for that object – right as it does for function calls as well.

After compilation there's then a second unit: the linker. As its name tells, it links all those compilation units together. If it now sees such a place holder it will replace it with the address of the object or function – which must exist, of course (for std::cout, there's an extern declaration in the header, but some other source file must have implemented it without extern – and if pre-compiled in some library), otherwise a linker error is thrown.

Upvotes: 1

Related Questions