Why do Xcode templates have #imports that duplicate Prefix.pch?

后端 未结 2 1039
情书的邮戳
情书的邮戳 2020-12-06 04:55

While learning iPhone programming, every Xcode template I\'ve seen includes an AppName-Prefix.pch file with the following contents:

#ifdef __OBJC__
    #impo         


        
相关标签:
2条回答
  • 2020-12-06 05:33

    My understanding is that this file's contents are prefixed to each of the source code files before compilation

    That's basically correct but you need to understand the subtle points: Every compilation from Xcode eventually boils down to an invocation of gcc or clang. What XCode does is to compile the X.pch file first:

    clang -x X.pch -o X.pch.gch
    

    and then when an individual source file (say a.m) is compiled, it issues

    clang -include X.pch a.m -o a.o
    

    which loads the pch file, triggering the use of the precompiled header. So, from the point of view of the compiler, it's not really that the content of the pch file is automatically prefixed. Rather, Xcode prefixes the precompiled header to a file when it invokes the compiler.

    A future version of XCode might just stop doing it. So, it's better to keep #imports in your .m or .h files, too.

    You can also think of it this way: the use of the pch file is just what Xcode does for us behind the scenes to speed up the compilation process. So, we shouldn't write codes in a way it essentially depends on it, like not importing UIKit.h file from our .m/.h files.

    (Also, it seems to me that XCode4's syntax coloring gets confused if you don't import the appropriate header files correctly from the .h and .m files.)

    0 讨论(0)
  • 2020-12-06 05:46

    Why have both?

    Better safe than sorry. Precompiled headers can be disabled, and since #import won't import anything twice, the overhead is negligible.

    0 讨论(0)
提交回复
热议问题