Mike
Mike

Reputation: 169

iOS: understanding global variables

In my first ViewController ViewControllerTest1 I've got a global variable called counter. counter is supposed to be increased every now and then in my app. Everything works fine:

@implementation ViewControllerTest1{
int counter = 0;

-(void)viewDidLoad
{...}

-(void)method {...}
}

Now if I declare another global variable called counter in my second ViewController ViewControllerTest2 XCode gives me an error.

I know I can just give it a different name, but why does that happen? Can I make sure only the globals of the certain ViewController that is active are in my memory?

Or am I doing something like a no go right now with globals like counter? Is there something better?

Upvotes: 1

Views: 560

Answers (2)

tomahh
tomahh

Reputation: 13661

If you want a symbol to be specific to a file, use the static keyword when declaring it.

Your declaration should look like

static int counter = 0;

At link time (after all the files were compiled), the global symbols are mixed up in the same file, and therefore, if two share the same name, an error is fired by the linker.

Upvotes: 3

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

If you define a variable at file scope (which includes locations within a class definition but outside the ivar area or a method body), it will have extern linkage by default, which requires unique symbol names.

Make it a static variable (static int ...) and the problem will be resolved, because static symbol names only need to be unique within the file in which they are declared.

If you are accessing this variable outside this file intentionally, and so need to maintain extern linkage, you will need to name the other variable something else to distinguish the two.

Upvotes: 0

Related Questions