使用 Clang 节省标头编译时间中的 @class 与 #import?
我在几个地方读到,建议在头文件中使用 @class Something 之类的声明,并且仅在 .m 文件中导入这些类以节省编译时间。
这真的仍然有必要吗?并且可以使 LLVM Clang 的编译速度更快,还是编译时间优势仅对较旧的编译器(如 GCC(旧版本))有效?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一不小心,你可能会得到循环导入:
预处理器将在 Ah 中包含 Bh,Ah 又包含 Ah(因为 Bh 导入了它),Ah 又再次导入 Bh,如此循环往复。
@class
语句可以防止意外错误,因为循环导入引起的错误确实非常不直观(从个人经验和回溯/错误检查来看)。Accidentally you can get circular import:
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).@Eimantas 关于循环依赖关系是正确的。也是为了性能。想象一下将
Ah
导入Bh
并将Bh
导入Cm
的情况。现在,每次修改Ah
时,Cm
都会重新编译,即使Cm
可能不依赖Ah
中的任何内容。使用@class可以避免这种构建混乱。迁移到 clang 并不会改变这一点。请注意,这仅适用于您可以更改的标头。通常,最好将系统标头直接导入到
.h
文件中。@Eimantas is correct about the circular dependencies. It's also for performance. Imagine the case where you import
A.h
intoB.h
andB.h
intoC.m
. Now, every time you modifyA.h
,C.m
is recompiled, even thoughC.m
may not rely on anything inA.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.