// 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!
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 thestatic
in this case because you will have a duplicate symbolglobalStr
in each object whose source code includedClassA.h
. You're not sharing anything - you're getting a new copy ofglobalStr
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
In
ClassA.h
, and define it in exactly one implementation file as: