Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...