extern
下面的代碼聲明了一個(gè)全局變量碑定,它用于告訴編譯器:“你現(xiàn)在編譯的文件中流码,有一個(gè)標(biāo)識(shí)符雖然沒(méi)有在本文件中定義,但是它是在別的文件中定義的全局變量延刘,你要在其它文件內(nèi)查找漫试!”
extern int a;//聲明一個(gè)全局變量a
請(qǐng)確保該變量已經(jīng)在其它文件內(nèi)定義!
如果該變量沒(méi)有在其他文件中定義碘赖,編譯器會(huì)報(bào)錯(cuò)驾荣。
比如,在某版本的 Xcode 下普泡,會(huì)有如下報(bào)錯(cuò):
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 (use -v to see invocation)
const
const 關(guān)鍵字指定變量的值是常量播掷,并通知編譯器防止程序員修改它。
當(dāng)我們嘗試直接修改時(shí)撼班,編譯器會(huì)報(bào)錯(cuò)??歧匈。比如下面的代碼在Xcode 8 中,會(huì)提示Cannot assign to variable 'const_i' with const-qualified type 'const int'
权烧。
const int const_i = 10;
const_i = 20;
程序運(yùn)行時(shí)眯亦,對(duì) const
關(guān)鍵字指定的變量?進(jìn)行修改的行為是未定義(undefined)的伤溉,它主要由編譯器所決定。
static
在全局變量前妻率,加上關(guān)鍵字static乱顾,該變量就被定義成為一個(gè)靜態(tài)全局變量。
靜態(tài)全局變量在聲明它的整個(gè)文件都是可見(jiàn)的宫静,而在文件之外是不可見(jiàn)的走净。
靜態(tài)變量都在全局?jǐn)?shù)據(jù)區(qū)分配內(nèi)存。
static NSString *name;
name = @"酷酷的哀殿";
NSLog(@"%p", name);
NSString *nameba = @"酷酷的哀殿";
NSLog(@"%p", &nameba);
NSString *nameb = @"酷酷的哀殿";
NSLog(@"%p", &nameb);
靜態(tài)變量和局部變量的地址并不在同一個(gè)區(qū)域
0x1000ec070
0x16fd1a1f8
0x16fd1a1f0
下面兩種全局變量聲明的區(qū)別是孤里,如果多個(gè)文件內(nèi)存在同名變量伏伯,int a
會(huì)導(dǎo)致duplicate symbol _a
static int a;
int a;
其它用法
定義外部使用的常量。
為了方便讓外部使用變量捌袜,推薦使用以下方法
//在.h文件內(nèi)進(jìn)行如下聲明
FOUNDATION_EXTERN NSString *const kSUNName;
//或
UIKIT_EXTERN NSString *const kSUNName;
并在.m文件內(nèi)定義
NSString *const kSUNName = @"酷酷的哀殿";
請(qǐng)注意说搅,這里不能添加static
修飾符。用static
修飾后虏等,將不能提供外界訪問(wèn)弄唧。比如下面的寫(xiě)法:
static const NSString *SUNName = @"酷酷的哀殿";
在其他地方使用會(huì)報(bào)錯(cuò)
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)
擴(kuò)展知識(shí)
但是,當(dāng)我們通過(guò) extern
關(guān)鍵字重新聲明其它文件內(nèi)的變量時(shí)霍衫,編譯器會(huì)忽略原先的關(guān)鍵字候引。所以,我們可以通過(guò)下面的方法修改可以取消報(bào)錯(cuò)??敦跌。
//A文件
const int sun_i = 10;
const int * const sun_j = &sun_i;
//B文件
extern int sun_i;
extern int *sun_j;
*sun_j = 100;
printf("%d",sun_i);