Share via


リンケージを指定する外部を使用する

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++ では リテラル文字列の フィールドの文字列 C 」 15 「C++ 」 「 をサポートします。標準ファイルはすべてを使用してランタイム ライブラリ関数が C++ プログラムで使用される 15 extern の 「 D 」の構文が含まれます。

次の例では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++ のキーワード

リンケージの設計

外部のストレージ クラスの指定子

概念

特定の動作

リンケージ