[英]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.
现在包括 header 文件,如 #include iostream 包括 header 文件 iostream.h。 This is telling the compiler for example „there is something called: cout“.
例如,这告诉编译器“有一个东西叫做:cout”。 QUESTION: How does the compiler get to the definition of cout (or all the other functions)?
问题:编译器如何获得 cout(或所有其他函数)的定义? In my understanding the compiler only gets to know names and types but no definitions.
以我的理解,编译器只知道名称和类型,但不知道定义。 Thanks in advance.
提前致谢。
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 .它需要知道对象的外观、它们提供的接口(因此对于
std::cout
来说,这是一个std::ostream
stream object 的子类)并且此类对象确实存在于某处。 That's it.就是这样。 What the compiler then does is adding placeholders for that object – right as it does for function calls as well.
编译器然后为 object 添加占位符——就像它为 function 调用所做的那样。
After compilation there's then a second unit: the linker. As its name tells, it links all those compilation units together.编译后有第二个单元:linker。顾名思义,它将所有这些编译单元链接在一起。 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.如果它现在看到这样的占位符,它将用 object 或 function 的地址替换它——当然这必须存在(对于
std::cout
,在 header 中有一个extern
声明,但其他一些源文件必须已经实现它没有extern
- 如果在某些库中预编译),否则会抛出 linker 错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.