外部儲存類別指定元
以 extern
儲存類別指定元宣告的函數具有外部鏈結,這表示可以從其他轉換單元呼叫該函數。 關鍵字 extern
是選用項目; 如果未指定儲存類別指定元,則會假設函數具有外部鏈結。
僅 C++ 開頭。
extern
宣告無法出現在類別範圍中。
您可以搭配使用 extern
關鍵字與指定鏈結類型的引數。
請參閱 ILE C/C++ Programmer 's Guide 中的 "Working with Multi-Language Applications" ,以取得 ILE C++ 支援的其他語言鏈結。
下列片段說明
extern "C"
的用法:extern "C" int cf(); //declare function cf to have C linkage
extern "C" int (*c_fp)(); //declare a pointer to a function,
// called c_fp, which has C linkage
extern "C" {
typedef void(*cfp_T)(); //create a type pointer to function with C
// linkage
void cfn(); //create a function with C linkage
void (*cfp)(); //create a pointer to a function, with C
// linkage
}
鏈結相容性會影響接受使用者函數指標作為參數的所有 C 程式庫函數,例如
qsort
。 請使用 extern "C"
鏈結規格來確保宣告的鏈結相同。 下列範例片段搭配使用 extern "C"
與 qsort
。#include <stdlib.h>
// function to compare table elements
extern "C" int TableCmp(const void *, const void *); // C linkage
extern void * GenTable(); // C++ linkage
int main() {
void *table;
table = GenTable(); // generate table
qsort(table, 100, 15, TableCmp); // sort table, using TableCmp
// and C library function qsort();
}
C++ 語言支援超載,其他語言則不支援。 其含意如下:
- 只要函數具有 C++ (預設) 鏈結,就可以超載該函數。 因此,容許下列一系列陳述式:
相反地,您無法超載具有非 C++ 鏈結的函數:int func(int); // function with C++ linkage int func(char); // overloaded function with C++ linkage
extern "C"{int func(int);} extern "C"{int func(int,int);} // not allowed //compiler will issue an error message
- 只有一個非 C + + -linkage 函數可以具有與超載函數相同的名稱。 例如:
不過,非 C + + -linkage 函數的參數不能與具有相同名稱的任何 C++ 函數的參數相同:int func(char); int func(int); extern "C"{int func(int,int);}
int func(char); // first function with C++ linkage int func(int, int); // second function with C++ linkage extern "C"{int func(int,int);} // not allowed since the parameter // list is the same as the one for // the second function with C++ linkage // compiler will issue an error message
僅限 C++ 結尾。