What is the difference between #import and #include in Objective-C?

Viewed 147541

What are the differences between #import and #include in Objective-C and are there times where you should use one over the other? Is one deprecated?

I was reading the following tutorial: http://www.otierney.net/objective-c.html#preamble and its paragraph about #import and #include seems to contradict itself or at least is unclear.

10 Answers

The #import directive was added to Objective-C as an improved version of #include. Whether or not it's improved, however, is still a matter of debate. #import ensures that a file is only ever included once so that you never have a problem with recursive includes. However, most decent header files protect themselves against this anyway, so it's not really that much of a benefit.

Basically, it's up to you to decide which you want to use. I tend to #import headers for Objective-C things (like class definitions and such) and #include standard C stuff that I need. For example, one of my source files might look like this:

#import <Foundation/Foundation.h>

#include <asl.h>
#include <mach/mach.h>

#include works just like the C #include.

#import keeps track of which headers have already been included and is ignored if a header is imported more than once in a compilation unit. This makes it unnecessary to use header guards.

The bottom line is just use #import in Objective-C and don't worry if your headers wind up importing something more than once.

#include vs #import

History:

#include => #import => Precompiled Headers .pch => @import Module(ObjC); => import Module(Swift)

[Precompiled Headers .pch]
[@import Module(ObjC);]
[import Module(Swift)]

#include + guard == #import

#include guardWiki - macro guard, header guard or file guard prevents to double include a header by a preprocessor that can slow down a build time

#import disadvantage

Works with file scope that is why we have slow build time because a compiler must parse and compile as many times as many .h files were imported in project scope

[#import in .h or .m]

Related