Use of extern in Objective C

You’ll find that extern is used extensively in the Cocoa frameworks, and one would be hard-pressed to find a convincing argument that their OO is “spoiled”. On the contrary, Cocoa is well-encapsulated and only exposes what it must, often via extern. Globally-defined constants are certainly the most common usage, but not necessarily the only valid use.

IMO, using extern doesn’t necessarily “spoil” object orientation. Even in OO, it is frequent to use variables that are accessible from anywhere. Using extern is the most frequent workaround for the lack of “class variables” (like those declared with static in Java) in Objective-C. It allows you to expand the scope in which you can reference a symbol beyond the compilation unit where it is declared, essentially by promising that it will be defined somewhere by someone.

You can also combine extern with __attribute__((visibility("hidden"))) to create a symbol that can be used outside its compilation unit, but not outside its linkage unit, so to speak. I’ve used this for custom library and framework code to properly encapsulate higher-level internal details.

Leave a Comment