SoFunction
Updated on 2025-04-06

A brief talk about the difference between #import, #include and @class in c/c++

1. Generally speaking, #import is used when importing objective c's header files, and #include is used when including c/c++ header files.

2. #import determines that a file can only be imported once, which will prevent you from having problems with recursive inclusion. <Tags>

Therefore, the advantage of #import over #include is that it does not cause cross-compilation.

#import && #class:

1. Import will contain all the information of this class, including entity variables and methods (in the .h file), while @class just tells the compiler that the name declared after it is the name of the class. As for how these classes are defined, I will tell you later.

2. In the header file, you usually only need to know the name of the referenced class. There is no need to know its internal entity variables and methods, so in the header file, @class is generally used to declare that this name is the name of the class. In the implementation class, since the entity variables and methods inside the referenced class will be used, #import needs to be used to include the header file of the referenced class.

Note: #import is to pass the header file of the referenced class, that is, to include the variables and methods in the .h file once, only once, and @class is not used, so the latter has higher compilation efficiency.

3. Considering the compilation efficiency, if you have 100 header files all #import the same header file, or these files are referenced in sequence, such as A->B, B->C, C->D. When the first header file changes, all the classes that reference it later need to be recompiled. If your class has many, it will take a lot of time. Instead, use @class.

4. If there are circular dependencies, such as: A->B, B->A, if #import is used to include each other, a compilation error will occur. If @class is used to declare each other in the header files of the two classes, there will be no compilation errors.

Note: Practice has proved that there will be no compilation errors in #import between A and B. Since the <mark> has already stated that the file is imported only once when #import, this article does not hold.

Summarize:

1. If it is not c/c++, try to use #import.

2. If you can #import in the implementation file, you will not #import in the header file.

3. If you can implement #import in the header file @class+, you will not #import in the header file.