Under what circumstances can an extern variable be used in definition?

后端 未结 6 1229
情书的邮戳
情书的邮戳 2020-12-21 12:16

I am very very sorry. I didn\'t know my incomplete code attachment would create such a mess. I am very glad to see so many sincere helps.

This code will compile:

6条回答
  •  盖世英雄少女心
    2020-12-21 12:44

    Everyone else has covered this pretty well, but just to show the variants in one place:

    int x;                    // #1
    

    is a declaration and definition. The initial value of x is zero.

    int x = 3;                // #2
    

    is a declaration and definition.

    const int cx;             // #3
    

    is illegal in C++.

    const int cx = 3;         // #4
    

    is a declaration and definition, but cx has internal linkage if this is its first declaration in the translation unit.

    extern int x;             // #5
    

    is a declaration but NOT a definition. There must be a definition of x somewhere else in the program.

    extern int x = 3;         // #6
    

    is a declaration and a definition. The extern is unnecessary, but makes things clear.

    extern const int cx;      // #7
    

    is a declaration but NOT a definition. There must be a definition of cx somewhere else in the program.

    extern const int cx = 3;  // #8
    

    is a declaration and a definition. The extern is needed unless the previous declaration above was already seen.

提交回复
热议问题