Mahin P Mahin P - 5 months ago 8
Objective-C Question

When i try to declare variables in h file it shows the error LINKER COMMAND FAILED WITH EXIT CODE -1

How can i globally declare a variable in objective c? when i try to declare variables in h file it shows the error


LINKER COMMAND FAILED WITH EXIT CODE -1

Answer

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!