何時在 C/C++ 中使用 extern


外部變數也稱為全域性變數。這些變數在函式外部定義,在整個函式執行期間都可以全域性使用。“extern”關鍵字用於宣告和定義外部變數。

[ extern “C” ] 關鍵字用於宣告以 C 語言實現和編譯的 C++ 中的函式。它在 C++ 語言中使用 C 庫。

以下是 extern 的語法。

extern datatype variable_name; // variable declaration using extern
extern datatype func_name(); // function declaration using extern

在此處,

資料型別 − 變數的資料型別,例如 int、char、float 等。

變數名稱 − 這是使用者給出的變數名稱。

函式名 − 函式名稱。

以下是一個 extern 示例

示例

 即時演示

#include <stdio.h>
extern int x = 32;
int b = 8;
int main() {
   extern int b;
   printf("The value of extern variables x and b : %d,%d\n",x,b);
   x = 15;
   printf("The value of modified extern variable x : %d\n",x);
   return 0;
}

輸出

The value of extern variables x and b : 32,8
The value of modified extern variable x : 15

在上面的程式中,兩個變數 x 和 b 被宣告為全域性變數。

extern int x = 32;
int b = 8;

在 main() 函式中,變數被稱為 extern 並列印值。

extern int b;
printf("The value of extern variables x and b : %d,%d\n",x,b);
x = 15;
printf("The value of modified extern variable x : %d\n",x);

更新於:2020 年 6 月 26 日

11K+ 瀏覽

職業起步

完成課程以獲得認證

開始
廣告
© . All rights reserved.