Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of extern in Objective C

Tags:

objective-c

How good is it to use extern in Objective C? It does make coding for some parts easy.. but doesn't it spoil the object orientation?

like image 636
Gaurav Ghate Avatar asked Dec 22 '09 13:12

Gaurav Ghate


People also ask

What is the function of an extern?

the extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit. When extern is used with a variable, it's only declared, not defined.

Is extern necessary in C?

You do not necessarily "need" extern for variables. When C was invented Unix linkers were also written, and they advanced the art in unheralded but clever ways. One contribution was defining all symbols as small "common blocks".

Why do we use extern and static keywords?

static means a variable will be globally known only in this file. extern means a global variable defined in another file will also be known in this file, and is also used for accessing functions defined in other files. A local variable defined in a function can also be declared as static .

What is extern method?

The extern modifier is used to declare a method that is implemented externally. A common use of the extern modifier is with the DllImport attribute when you are using Interop services to call into unmanaged code. In this case, the method must also be declared as static , as shown in the following example: C# Copy.


1 Answers

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.

like image 73
Quinn Taylor Avatar answered Oct 05 '22 12:10

Quinn Taylor