共用方式為


使用 extern 指定連結

extern string-literal { declaration-list }
extern string-literal declaration

備註

extern 關鍵字可宣告變數或函式,並指定其具有外部連結 (在已定義檔案之外的檔案中皆為可見)。 修改變數時,extern 可指定變數的靜態持續期間 (該變數會在程式啟動時配置,並在程式結束時解除配置)。 變數或函式可能會在另一個原始程式檔中定義,或在相同的檔案中定義。 在檔案範圍上宣告的變數和函式預設為外部宣告。

範例

// specifying_linkage1.cpp
int i = 1;
void other();

int main() {
   // Reference to i, defined above:
   extern int i;
}

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

   // i will be redefined; global i no longer visible:
   // int i = 16;
}

在 C++ 中,透過字串使用時,extern 會將其他語言的連接慣例指定為供宣告子使用。 只有在先前宣告為具有 C 連結時,才可以存取 C 函式和資料。 不過,您必須在另行編譯的轉譯單位中定義它們。

Microsoft C++ 在 string-literal 欄位中支援字串 "C""C++"。 所有使用 extern "C" 語法的標準 Include 檔都可在 C++ 程式中使用執行階段程式庫函式。

下列範例顯示宣告具有 C 連結之名稱的替代方式:

// specifying_linkage2.cpp
// compile with: /c
// Declare printf with C linkage.
extern "C" int printf( const char *fmt, ... );

//  Cause everything in the specified header files
//   to have C linkage.
extern "C" {
   // add your #include statements here
   #include <stdio.h>
}

//  Declare the two functions ShowChar and GetChar
//   with C linkage.
extern "C" {
   char ShowChar( char ch );
   char GetChar( void );
}

//  Define the two functions ShowChar and GetChar
//   with C linkage.
extern "C" char ShowChar( char ch ) {
   putchar( ch );
   return ch;
}

extern "C" char GetChar( void ) {
   char ch;

   ch = getchar();
   return ch;
}

// Declare a global variable, errno, with C linkage.
extern "C" int errno;

請參閱

參考

C++ 關鍵字

連結規格

extern 儲存類別規範

概念

識別項的行為

連結