今天做項目,發了個很大的神經,雖然對static的概念 “静态全局变量在声明它的整个文件都是可见的,而在文件之外是不可见的;” 記得牢牢的,但還是犯了這種錯誤。
項目目錄結構:
TEST--> t_main.c , t.h
--> TEST2 --> t2.c
t_main.c 代碼:
#include "stdio.h"
#include "string.h"
#include "t.h"
void main()
{
printf("%d\n",MaxInt); // 1
t2_f();
printf("%d\n",MaxInt);
}
t.h 代碼:
static int MaxInt = 100;
t2.c 代碼:
#include "..\t.h"
void t2_f()
{
MaxInt = 200; //2
}
最後輸出的結果都是 100.
註釋 1,2 處的 MaxInt 在內存的地址不同,所以 t2_f() 函數中更改的是 t2.c 文件 中的 MaxInt , static 變量嘛,就是本文件可防,外部文件 t2.c 就不可防了
#include "file" 預編譯是將 file中的內容替換 #include "file"語句,我覺得跟#define 功能差不多
所以上述代碼 t_main.c 就相當於
static int MaxInt = 100;
void main()
{...................}
t2.c 中的代碼相當於
MaxInt = 100; //這裡的MaxInt 編譯器會為其开辟新的內存空間,囧。。。
void t2_f() {................}