extern を使用したリンケージの指定
extern string-literal { declaration-list }
extern string-literal declaration
解説
extern キーワードは、変数または関数を宣言し、それが外部リンケージを持つことを指定します (その名前は、それが定義されたファイル以外のファイルから見ることができます)。 変数を変更するとき、extern は変数が静的存続期間を持つことを指定します (プログラムの開始時に割り当てられ、プログラムの終了時に解放されます)。 変数または関数は、別のソース ファイルで定義されることも、後で同じファイル内で定義されることもあります。 ファイル スコープでの変数と関数の宣言は既定で external です。
使用例
// 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++" をサポートします。 すべての標準の include ファイルは、extern "C" 構文を使用して、ランタイム ライブラリ関数が 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;