keldar
keldar

Reputation: 6242

Import in header file vs. import in source file

What is the general rule for using an #import in a header file, as opposed to using an #import in a source file?

Upvotes: 2

Views: 1539

Answers (2)

meaning-matters
meaning-matters

Reputation: 22936

By #importing 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 #imports. 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 #imports 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.

Upvotes: 2

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43498

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.

Upvotes: 1

Related Questions