#import和#include在Objective-C中的区别是什么?在某些情况下你应该使用其中一个而不是另一个?一个被弃用了吗?

我正在阅读以下教程:http://www.otierney.net/objective-c.html#preamble,其中关于#import和#include的段落似乎自相矛盾,至少不清楚。


当前回答

在可能的情况下,我在我的.h文件中有一个全局变量,导致了这个问题,我通过在它前面添加extern来解决它。

其他回答

如果你在.h文件中两次包含一个文件,编译器将会给出错误。 但是如果你多次导入一个文件,编译器就会忽略它。

#include vs #import预处理器指令

历史:

#include -> #import ->[预编译Headers .pch] -> [@import Module(ObjC);] -> [import Module(Swift)]

#import是#include的下一代,它解决了当前.h文件的双重包含和递归包含问题。只是当前文件中包含的。h主体的单一副本

#import == #include + guard

守卫长这样

#ifndef <some_unique_name>
#define <some_unique_name>

<header_body>

#endif

#include guardWiki(宏保护,头保护,文件保护)-防止预处理器包含多个头,这会减慢构建时间

#include和#import使用了一种复制/粘贴机制——递归地复制.h文件主体(除了#include, #import指令之外的所有内容)。这意味着结果文件将不包含#include, #import指令)

如果选择。m文件Product -> Perform Action ->预处理“。m”,可以检查结果。

# include示例

//A.h
@interface A : NSObject
- (int)startA;
@end

//ViewController.h
#include "A.h"

ViewController。M预处理后

@interface A : NSObject
- (int)startA;

@end

@interface ViewController : UIViewController
@end

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

}
@end

双重包含示例

//A.h
@interface A : NSObject //Build time error: Duplicate interface definition for class 'A'
@end 

//B.h
#include "A.h"

//C.h
#include "A.h"
//#import "A.h" to solve
#include "B.h"

递归包含示例

//A.h
#include "B.h" //Build time error: #include nested too deeply
//#import "B.h" to fix it

@interface B : NSObject //Build time error: Duplicate interface definition for class 'A'
@end


//B.h 
#include "A.h" //Build time error: #include nested too deeply
//#import "A.h" to fix it

@interface B : NSObject //Build time error: Duplicate interface definition for class 'B'
@end

[#import in .h or .m]

#include用于从另一个文件中获取“东西”到使用#include的文件中。 例:

文件:main.cpp

#include "otherfile.h"

// some stuff here using otherfile.h objects,
// functions or classes declared inside

头保护用于每个头文件(*.h)的顶部,以防止包含同一个文件超过一次(如果发生这种情况,您将得到编译错误)。

文件:otherfile.h

#ifndef OTHERFILE
#define OTHERFILE

// declare functions, classes or objects here

#endif

即使你在代码中添加了#include "otherfile.h" n次,其中的this也不会被重新声明。

我同意杰森的观点。

我这样做被抓了个现行:

#import <sys/time.h>  // to use gettimeofday() function
#import <time.h>      // to use time() function

对于GNU gcc,它一直抱怨time()函数是 没有定义。

然后我把#import改为#include,一切正常。

原因:

#import <sys/time.h>: <sys/time.h>通过使用#定义只包含<time.h>的一部分

#import <time.h>: 没有去。尽管<time.h>只包含了一部分,as 就#import而言,该文件现在已经完全包含在内。

底线:

C/ c++头文件通常包含其他包含文件的部分。 所以对于C/ c++头文件,使用#include。 对于objc/objc++头文件,使用#import。

在可能的情况下,我在我的.h文件中有一个全局变量,导致了这个问题,我通过在它前面添加extern来解决它。