file1.c的內(nèi)容如下:
#include "file1.h"
void printStr()
{
int normal = 0;
static int stat = 0; //this is a static local var
printf("normal = %d ---- stat = %d\n",normal, stat);
normal++;
stat++;
}
#include "file1.h"
int main()
{
printStr();
printStr();
printStr();
printStr();
printf("call stat in main: %d\n",stat);
return 0;
}
復(fù)制代碼
這個調(diào)用會報錯,因為file2.c中引用了file1.c中的靜態(tài)局部變量stat,如下:
[liujx@server235 static]$ gcc -Wall file2.c file1.c -o file2
file2.c: In function ‘main’:
file2.c:9: 錯誤:‘stat’ 未聲明 (在此函數(shù)內(nèi)第一次使用)
file2.c:9: 錯誤:(即使在一個函數(shù)內(nèi)多次出現(xiàn),每個未聲明的標識符在其
file2.c:9: 錯誤:所在的函數(shù)內(nèi)只報告一次。)
編譯器說stat未聲明,這是因為它看不到file1.c中的stat,下面注掉這一行:
#include "file1.h"
int main()
{
printStr();
printStr();
printStr();
printStr();
// printf("call stat in main: %d\n",stat);
return 0;
}
liujx@server235 static]$ gcc -Wall file2.c file1.c -o file2
[liujx@server235 static]$ ./file2
normal = 0 ---- stat = 0
normal = 0 ---- stat = 1
normal = 0 ---- stat = 2
normal = 0 ---- stat = 3
運行如上所示。可以看出,函數(shù)每次被調(diào)用,普通局部變量都是重新分配,而靜態(tài)局部變量保持上次調(diào)用的值不變。
file1.c的內(nèi)容如下:
#include "file1.h"
void printStr()
{
int normal = 0;
static int stat = 0; //this is a static local var
printf("normal = %d ---- stat = %d\n",normal, stat);
normal++;
stat++;
}
#include "file1.h"
int main()
{
printStr();
printStr();
printStr();
printStr();
printf("call stat in main: %d\n",stat);
return 0;
}
復(fù)制代碼
這個調(diào)用會報錯,因為file2.c中引用了file1.c中的靜態(tài)局部變量stat,如下:
[liujx@server235 static]$ gcc -Wall file2.c file1.c -o file2
file2.c: In function ‘main’:
file2.c:9: 錯誤:‘stat’ 未聲明 (在此函數(shù)內(nèi)第一次使用)
file2.c:9: 錯誤:(即使在一個函數(shù)內(nèi)多次出現(xiàn),每個未聲明的標識符在其
file2.c:9: 錯誤:所在的函數(shù)內(nèi)只報告一次。)
編譯器說stat未聲明,這是因為它看不到file1.c中的stat,下面注掉這一行:
#include "file1.h"
int main()
{
printStr();
printStr();
printStr();
printStr();
// printf("call stat in main: %d\n",stat);
return 0;
}
liujx@server235 static]$ gcc -Wall file2.c file1.c -o file2
[liujx@server235 static]$ ./file2
normal = 0 ---- stat = 0
normal = 0 ---- stat = 1
normal = 0 ---- stat = 2
normal = 0 ---- stat = 3
運行如上所示。可以看出,函數(shù)每次被調(diào)用,普通局部變量都是重新分配,而靜態(tài)局部變量保持上次調(diào)用的值不變。