Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use global variables in Objective-C?

Tags:

How should I declare a global variable in my Objective-C project?

like image 458
sri Avatar asked Jul 30 '10 05:07

sri


People also ask

How do I declare a global variable in Objective C?

Somewhere in your header, you would declare a global variable like this: extern int GlobalInt; The extern part tells the compiler that this is just a declaration that an object of type int identified by GlobalInt exists.

Can you declare global variables in C?

The C language allows the redeclaration of the global variable. It means that this variable can get declared again when the first declaration doesn't lead to the initialization of the variable. It is possible because the second program works pretty well in the C language even if the first one fails during compilation.


1 Answers

Traditionally, global variables are declared in a header, and defined in a source file. Other source files only need to know how it is declared to use it (i.e. its type and its name). As long as the variable is defined somewhere in a source file, the linker will be able to find it and appropriately link all the references in other source files to the definition.

Somewhere in your header, you would declare a global variable like this:

extern int GlobalInt; 

The extern part tells the compiler that this is just a declaration that an object of type int identified by GlobalInt exists. It may be defined later or it may not (it is not the compiler's responsibility to ensure it exists, that is the linker's job). It is similar to a function prototype in this regard.

In one of your source files, you define the GlobalInt integer:

int GlobalInt = 4; 

Now, each file that includes the header will have access to GlobalInt, because the header says it exists, so the compiler is happy, and the linker will see it in one of your source files, so it too will be happy. Just don't define it twice!

However


You should consider whether or not this approach is useful. Global variables get messy for a number of reasons (trying to find out exactly where it is defined or declared, threading issues), there is usually not a need for global variables. You should perhaps consider using a singleton approach.

like image 77
dreamlax Avatar answered Oct 25 '22 15:10

dreamlax