简体   繁体   English

C++ 为什么我们在 header 文件中包含所有声明

[英]C++ why we include all declarations in header files

#include <iostream>

When you do this and it becomes the source passing through the preprocessor, our file will be 5k.当你这样做并且它成为通过预处理器的源时,我们的文件将为 5k。 The compiler doesn't do all this declaration, right?编译器不会做所有这些声明,对吧? (There are always some things we don't use after all) (总有一些东西我们终究用不到)

| | Is the linker or compiler preventing this? linker 或编译器是否阻止了这种情况?

**so when you include all declaration file in header ** **所以当您在 header 中包含所有声明文件时 **

  1. improve build times.改善构建时间。
  2. link against code without having the source for the definitions.在没有定义源的情况下链接代码。
  3. avoid marking everything "inline".避免将所有内容标记为“内联”。

compiler only see the declaration as it know definition might be somewhere, then it use all definition at the linking time.编译器只看到声明,因为它知道定义可能在某处,然后它在链接时使用所有定义。

The rule of thumb is this: Header files should contain declarations, source files should contain definitions.经验法则是:Header 文件应包含声明,源文件应包含定义。

Two types of Declarations:两种类型的声明:

  1. DECLARATIONS: A declaration introduces a name into a scope. Generally speaking, a scope is either an entire.cpp file or anything in code delimited by {}, be it a function, a loop within a function, or even an arbitrarily placed block of {} within a function. A name introduced, is visible within the scope from the point at which it is declared to the end of that scope. A declarations merely tells the compiler how to use something, it does not actually create anything.声明:声明将名称引入 scope。一般来说,scope 要么是一个完整的.cpp 文件,要么是代码中由 {} 分隔的任何内容,无论是 function、function 中的循环,还是任意放置的块{} 在 function 中。引入的名称在 scope 中可见,从声明它的那一点到 scope 的末尾。声明仅告诉编译器如何使用某些东西,它实际上并不创建任何东西。
    extern int y; // declares y, but does not define it.  y is defined elsewhere,
                  // but the program can now use it since it knows what it is (an integer)
  1. PROTOTYPES: A prototype is just another name for a declaration of a function.原型:原型只是 function 声明的另一个名称。
    double someFunction( double, int );

referred from: http://www.cplusplus.com/articles/yAqpX9L8/参考自: http://www.cplusplus.com/articles/yAqpX9L8/

Also get more information on this site: http://www.cplusplus.com/articles/Gw6AC542/也可在此站点上获取更多信息: http://www.cplusplus.com/articles/Gw6AC542/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM