How should I declare a global variable in my Objective-C project?
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.
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.
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!
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.
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