views:

56

answers:

1
// in ClassA.h  
static NSString *globalStr = @"HelloWorld";

@interface ClassA  
    ...  
@end

// in ClassB.h  
#include "ClassA.h"

// in ClassB.m  
...  
NSLog(@"The global string: %@", globalStr);
...

In C++, "static" should mean the variable or function has a internal linkage.
But it is used to share the variable in this case, error will occur without the static keyword.

I'm confused, could someone tell me the concept behind?
Thanks!

+3  A: 

static means exactly the same thing in Objective-C that in means in C - it has internal linkage and static storage duration. You get an error without the static in this case because you will have a duplicate symbol globalStr in each object whose source code included ClassA.h. You're not sharing anything - you're getting a new copy of globalStr for each compilation unit.

Don't put object definitions in your headers and you'll be better off. If you want a single global string, you need to put

extern NSString *globalStr;

In ClassA.h, and define it in exactly one implementation file as:

NSString *globalStr = @"HelloWorld";
Carl Norum
It helps to remember that headers are *literally copied* into the file they're included in. You're not "sharing" the variable with other files that import the header — the header is causing all those files to each contain the declaration `static NSString *globalStr = @"HelloWorld"`.
Chuck
I guess I should have added that you would have the same bug in C++....
Carl Norum
Thanks, but I didn't really know why there is a "duplicate symbol". Could you explain more, thanks again.