@class vs. #import in header compile time saving with Clang?

笑着哭i 提交于 2019-12-23 17:52:10

问题


I have read in a couple of places that it is advisable to use declarations like @class Something in header files and only importing these classes in the .m file to save compile time.

Is that really still necessary and makes compiling faster with LLVM Clang or was the compile time advantage only valid for older compilers like (old versions of) GCC?


回答1:


@Eimantas is correct about the circular dependencies. It's also for performance. Imagine the case where you import A.h into B.h and B.h into C.m. Now, every time you modify A.h, C.m is recompiled, even though C.m may not rely on anything in A.h. Using @class avoids this kind of build churn. The move to clang doesn't change this.

Note that this only applies to headers you can change. It's generally fine and preferred to import system headers directly into you .h files.




回答2:


Accidentally you can get circular import:

// A.h
#import "B.h"

// B.h
#import "A.h"

Preprocessor will include B.h in A.h, which in turn include A.h (because B.h imports it), which in turn import B.h again, etc. ad infinitum.

@class statements prevent that accidental error, since error caused by circular import is really REALLY unintuitive (speaking from personal experience and backtrace/error inspections).



来源:https://stackoverflow.com/questions/7271146/class-vs-import-in-header-compile-time-saving-with-clang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!