- extern
下面的代码声明了一个全局变量,它用于告诉编译器:“你现在编译的文件中,有一个标识符虽然没有在本文件中定义,但是它是在别的文件中定义的全局变量,你要在其它文件内查找!”
extern int a;//声明一个全局变量a
但是如果该变量没有在其他文件中定义,则会报错
Undefined symbols for architecture arm64:
"_b", referenced from:
-[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
- const
使用const在任意文件中定义 ,外部都能访问。并且编译时会进行类型检查。
//A.h
const NSString *SUNName = @"酷酷的哀殿";
但是在其它文件使用前,需要使用extern声明。
//B.m
extern NSString *SUNName;
NSLog(@"%@",SUNName);
- static
- 在全局变量前,加上关键字static,该变量就被定义成为一个静态全局变量。
- 静态全局变量在声明它的整个文件都是可见的,而在文件之外是不可见的。
- 静态变量都在全局数据区分配内存。
static NSString *name;
name = @"酷酷的哀殿";
NSLog(@"%p", name);
NSString *nameba = @"酷酷的哀殿";
NSLog(@"%p", &nameba);
NSString *nameb = @"酷酷的哀殿";
NSLog(@"%p", &nameb);
静态变量和局部变量的地址并不在同一个区域
0x1000ec070
0x16fd1a1f8
0x16fd1a1f0
下面两种全局变量声明的区别是,如果多个文件内存在同名变量,int a
会导致duplicate symbol _a
static int a;
int b;
- 其它用法
为了方便让外部使用变量,推荐使用以下方法
在.h文件内进行如下声明
FOUNDATION_EXTERN NSString *const kSUNName;
//或
UIKIT_EXTERN NSString *const kSUNName;
并在.m文件内定义
NSString *const kSUNName = @"酷酷的哀殿";
用static const修饰后,不能提供外界访问。
static const NSString *SUNName = @"酷酷的哀殿";
在其他地方使用会报错
Undefined symbols for architecture arm64:
"_SUNName", referenced from:
-[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)