1)全局变量是不显式用static修饰的全局变量,全局变量默认是有外部链接性的,作用域是整个工程,在一个文件内定义的全局变量,在另一个文件中,通过extern 全局变量名的声明,就可以使用全局变量。
2)全局静态变量是显式用static修饰的全局变量,作用域是声明此变量所在的文件,其他的文件即使用extern声明也不能使用。
// Book.h
NSString *const bookName = @"Cocoa";
@interface Book : NSObject
@end
// Student.h
extern NSString *bookName;
@interface Student : NSObject
@end
// Student.m
#import "Student.h"
@implementation Student
- (NSString *)description
{
return [NSString stringWithFormat:@"%@", bookName];
}
@end
#import "ViewController.h"
#import "Student.h"
@interface ViewController ()
@end
// viewController.m
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Student *s = [[Student alloc] init];
NSLog(@"s = %@", s);
}
// 结果: s = Cocoa
但是如果写成
static NSString *const bookName = @"Cocoa";
再编译就会报错了。