共用方式為


extern 儲存類別指定名稱

extern 記憶體類別規範宣告的變數,是另一個原始程式檔中定義相同名稱的變數參考。 它可用來公開外部層級的變數定義。 宣告為 extern 的變數本身沒有配置記憶體;它只是名稱。

範例

下列範例說明內部和外部層級宣告:

// Source1.c

int i = 1;

// Source2.c

#include <stdio.h>

// Refers to the i that is defined in Source1.c:
extern int i;

void func(void);

int main()
{
    // Prints 1:
    printf_s("%d\n", i);
    func();
    return;
}

void func(void)
{
    // Address of global i assigned to pointer variable:
    static int *external_i = &i;

    // This definition of i hides the global i in Source.c:
    int i = 16;

    // Prints 16, 1:
    printf_s("%d\n%d\n", i, *external_i);
}

在此範例中,變數 i 定義在 Source1.c 中且初始值為 1。 extern Source2.c 中的宣告會在該檔案中顯示 'i'。

在函式中 func ,全域變數 i 的位址是用來初始化 static 指標變數 external_i。 這可運作,因為全域變數有 static 存留期,這表示其位址不會在程式執行期間變更。 接下來,變數 i 是定義在 func 範圍內的區域變數,且初始值為 16。 這個定義不會影響外部層級 i 的值,將其名稱用於區域變數會將之隱藏。 全域 i 的值現在只能透過指標 external_i 來存取。

另請參閱

內部層級宣告的儲存類別規範