C語言中,static關鍵字舉例——全域static變數

來源:互聯網
上載者:User

C語言中,可以在全域範圍中使用static關鍵字:被static關鍵字修飾的變數或函數,僅在本".c檔案"中可見,而在其他".c檔案"中,不可見。例如,在t1.c中的全域範圍,定義static函數func,則在t2.c中,無法使用t1.c中定義的func函數,即使在t2.c中,使用extern關鍵字聲明了func函數。

實驗代碼如下:

1、預設使用extern修飾符

/*file:t1.c*//*定義函數func,此時沒有使用任何修飾符,**所以預設使用extern修飾*/void func(){}

/*file:t2.c*//*聲明func函數,該函數在t1.c中定義**由於聲明的是函數,所以,此時extern關鍵字,可以省略*/extern void func();int main(){func();//調用func函數return 0;}

編譯結果:

編譯通過

2、使用static修飾後,則僅在本".c檔案"中可見

/*file:t1.c*//*定義函數func,此時使用static修飾*/static void func(){}

/*file:t2.c*//*聲明func函數,該函數在t1.c中定義,且被用static修飾*/extern void func();int main(){func();//error.func在t2.c中不可見return 0;}

編譯結果:

3、如何在“定義static函數的.c檔案”中,聲明static函數

從上面兩則常式中可以看出,static確實可以讓函數(或變數)僅在本“.c檔案”中可見,而在其他".c檔案"中不可見。然而經常地,我們需要“在某函數的定義代碼之前,使用這個函數”,這就需要我們“聲明該函數,然後使用調用該函數,然後定義該函數”,所以,這就涉及到,如何聲明static函數,當然啦,肯定是在“定義該static函數的.c檔案中,聲明該static函數”。

/*file:t1.c*//***************************static聲明*******************************///static 聲明,static定義static void func1();static void func1(){}//func1是static函數,在其他.c檔案中,不可見//static 聲明,預設定義static void func2();void func2(){}//func2也是static函數,在其他.c檔案中,不可見//static 聲明,extern定義static void func3();extern void func3(){}//func3還是static,儘管它被定義為extern/***************************extern聲明*******************************///extern 聲明,extern定義extern void func4();extern void func4(){}//func4是extern//extern 聲明,預設定義extern void func5();void func5(){}//func5是extern//extern 聲明,static定義extern void func6();static void func6(){}//func6是static/****************************預設聲明*******************************///預設聲明,預設定義void func7();void func7(){}//func7是extern//預設聲明,extern定義void func8();extern void func8(){}//func8是extern//預設聲明,static定義void func9();static void func9(){}//func9是static

/*file:t2.c*//*聲明func[1-9]函數,這些函數在t1.c中定義*/extern void func1();extern void func2();extern void func3();extern void func4();extern void func5();extern void func6();extern void func7();extern void func8();extern void func9();int main(){//凡是被static定義/聲明的函數,都是static的,在其他".c檔案"中均不可見:func1();//error.func1在t2.c中不可見func2();//error.func2在t2.c中不可見func3();//error.func3在t2.c中不可見func4();func5();func6();//error.func9在t2.c中不可見func7();func8();func9();//error.func9在t2.c中不可見return 0;}

編譯結果:

結論是:
1、使用static修飾的函式宣告或定義,都會將該函數變為static函數,僅可在本“.c檔案”中可見,如func1,func2,func3,func6,func9;
2、使用static修飾“未用static聲明”的函數的定義,則會得到warning,如func6和func9.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.