Why does initializing an extern variable inside a function give an error?

前端 未结 5 1443
温柔的废话
温柔的废话 2020-12-05 10:10

This code compiles fine:

extern int i = 10;

void test()
{
    std::cout << \"Hi\" << i << std::endl;
}

While this code g

5条回答
  •  离开以前
    2020-12-05 10:41

    At first ,you should familiar with the conception of linkage and the meaning of extern linkage:

    A name is said to have linkage when it might denote the same object, reference, function, type, template, namespace or value as a name introduced by a declaration in another scope:

    When a name has external linkage, the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.
    --3.5.6.2 n3242

    The function of static which is differ from extern,extern is just a request,static is a command.

    The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage.

    • If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration.
    • If there is more than one such matching entity, the program is ill-formed.
    • Otherwise, if no matching entity is found, the block scope entity receives external linkage.

    --3.5.6.6 n3242

    Therefore,in block scope the procedure below is recommend to do:

         extern int i;//declare it,request the linkage according to 3.5.6.6 above
         i = 10;//modify it when has link to a defination
    

    For the global extern declaration is possibly convert form

         extern int i =10;
    

    to

         extern int i;//include in .hpp is recommended 
         int i =10;//global or namespace variable defination
    

提交回复
热议问题