简体   繁体   中英

Import in header file vs. import in source file

什么是使用的一般规则#import在头文件,而不是使用#import在源文件?

By #import ing a header you create a dependency. As a 'general rule' it's good to minimise dependencies.

There's more to it than just placement of #import s. Few remarks:

  1. Put as little definitions/properties/imports/... in your headers as possible; ergo, move as much as possible to the source file. A header is the public API of your module/class, you want to keep it as clean/to-the-point as possible. This avoids all kinds of dependencies that are actually not necessary.

  2. It's often sufficient to add @class ClassYouNeed; (typically just below the #import s you do really need) instead of #import "ClassYouNeed.h" . This is when just that class is used as a type, and no other definitions from ClassYouNeed.h . Typically you'd add @class ClassYouNeed; in the header and then do the full #import ClassYouNeed.h in the source file, because in the source file you typically need more than just the class/type. The compiler will sort things out for you.

In a header file, import only headers which are needed for the header file itself (the interface) and not for the implementation. Within the source file (the implementation) import the respective header file and any other headers which are needed only for the implementation.

This way, when the outside world includes your header, it will only expose what's relevant to its interface and not what's relevant to the implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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