Use of 'extern' keyword while defining the variable

前端 未结 2 502
既然无缘
既然无缘 2020-12-12 01:11

After seeing this answer I have this doubt. In my project, I have seen some extern variables declared and defined like below:

file1.h

2条回答
  •  春和景丽
    2020-12-12 01:25

    It depends. In this case, it makes no difference, but it can.

    There are two issues here: definition vs. just declaration, and linkage. And C++ doesn't handle them in an orthogonal manner. In C++, the declaration of a variable or a reference is a definition if and only if neither the extern keyword nor an initialization are present. (Note that the rules are different for functions, types and templates.) So:

    extern int a;       //  not a definition
    int a;              //  definition
    extern int a = 42;  //  definition
    int a = 42;         //  definition
    

    The rules say you must have exactly one definition, so you put a definition in a source file, and the declaration in a header.

    With regards to linkage, a symbol declared as a variable or a reference has external linkage if it is declared at namespace scope, is not declared static, and is either not const (nor constexpr in C++11) or has been declared extern. The fact that const can give a variable internal linkage occasionally means that the extern is necessary:

    int const a = 42;           //  internal linkage
    extern int const a = 42;    //  external linkage
    

    Note that the extern doesn't have to be on the same declaration:

    extern int const a;         //  declaration, in header...
    int const a = 42;           //  external linkage, because of
                                //  previous extern
    

    Still, I've occasionally needed the extern; typically because I want to use a local constant to instantiate a template. (This is only an issue if the template parameter takes a pointer or a reference. You can instantiate a template with an int parameter with an int const a = 42;, because the template is instantiated with the value 42, and not the variable a.)

提交回复
热议问题