While learning iPhone programming, every Xcode template I've seen includes an AppName-Prefix.pch file with the following contents:
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#endif
My understanding is that this file's contents are prefixed to each of the source code files before compilation. Yet each of the other files also imports UIKit, which seems superfluous. For example, main.m
begins...
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
...
Cocoa applications in Mac OS X do the same thing, importing Cocoa.h in both the prefix file and the header files.
Why have both? I removed the #import
directives from all of the source files except the prefix file, and it compiled and ran correctly.
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 #import
s 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.)
Why have both?
Better safe than sorry. Precompiled headers can be disabled, and since #import won't import anything twice, the overhead is negligible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With