25

私はexternsに関するいくつかの情報を読んでいました。ここで、著者は変数の宣言と定義について言及し始めました。宣言により、彼は次の場合を参照しました。変数が宣言されている場合、そのスペースが割り当てられていません。Cで変数を使用するときのほとんどの場合、実際にはそれらを正しく定義および宣言していると思うので、これは私を混乱させました。つまり、

int x; // definition + declaration(at least the space gets allocated for it)

変数を宣言するが定義しない場合のCの場合のみ、次を使用する場合だと思います。

extern int x; // only declaration, no space allocated

私はそれを正しく理解しましたか?

4

3 に答える 3

23

基本的に、はい、あなたは正しいです。

extern int x;  // declares x, without defining it

extern int x = 42;  // not frequent, declares AND defines it

int x;  // at block scope, declares and defines x

int x = 42;  // at file scope, declares and defines x

int x;  // at file scope, declares and "tentatively" defines x

C 標準で記述されているように、宣言は一連の識別子の解釈と属性を指定し、オブジェクトの定義により、そのオブジェクト用にストレージが予約されます。また、識別子の定義は、その識別子の宣言です

于 2013-10-11T20:40:34.977 に答える
0

これは、私がインターネットで見つけた断片をまとめたものです。私の見方は歪んでいるかもしれません。
いくつかの基本的な例。

int x;
// The type specifer is int
// Declarator x(identifier) defines an object of the type int
// Declares and defines

int x = 9;
// Inatializer = 9 provides the initial value
// Inatializes 

C11 標準 6.7 では、識別子の定義は、次のような識別子の宣言です。

— オブジェクトの場合、ストレージがそのオブジェクト用に予約されます。

— 関数の場合、関数本体が含まれます。

int main() // Declares. Main does not have a body and no storage is reserved

int main(){ return 0; } 
  // Declares and defines. Declarator main defines                  
  // an object of the type int only if the body is included.

以下の例

int test(); Will not compile. undefined reference to main
int main(){} Will compile and output memory address.

// int test();
int main(void)   
{
    // printf("test %p \n", &test); will not compile 
    printf("main %p \n",&main);
    int (*ptr)() = main;

    printf("main %p \n",&main);

 return 0;
}

extern int a;  // Declares only.
extern int main(); //Declares only.

extern int a = 9;  // Declares and defines.
extern int main(){}; //Declares and  defines.                                     .
于 2016-10-15T04:48:04.503 に答える