C 中的靜態函式
C 中的靜態函式是作用域僅限於物件檔案的函式。這意味著靜態函式僅在其物件檔案中可見。透過在函式名稱前放置 static 關鍵字,可以將函式宣告為靜態函式。
演示此功能的示例如下 −
有兩個檔案 first_file.c 和 second_file.c。這些檔案的內容如下 −
first_file.c 的內容
static void staticFunc(void)
{
printf("Inside the static function staticFunc() ");
}second_file.c 的內容
int main()
{
staticFunc();
return 0;
}現在,如果編譯上述程式碼,則會獲得一個錯誤,即“對 staticFunc() 的未定義引用”。這是因為函式 staticFunc() 是一個靜態函式,並且僅在其物件檔案中可見。
演示 C 中靜態函式的程式如下 −
示例
#include <stdio.h>
static void staticFunc(void){
printf("Inside the static function staticFunc() ");
}
int main()
{
staticFunc();
return 0;
}輸出
上述程式的輸出如下 −
Inside the static function staticFunc()
在上述程式中,函式 staticFunc() 是一個靜態函式,用於列印“在靜態函式 staticFunc() 內部”。main() 函式呼叫 staticFunc()。此程式可以正確執行,因為靜態函式僅從其自身的物件檔案中呼叫。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP