No linkage at block scope?

后端 未结 2 1930
时光说笑
时光说笑 2021-02-20 06:25

Do all variables declared in a block have \'no linkage\'?

For example:

1:

If I declare a static variable:

void foo()
{
   static int i;         


        
2条回答
  •  花落未央
    2021-02-20 06:54

    Indeed, 'no linkage' at function scope.

    The goal is lifetime management: the static has the lifetime of a global static, while it has the visibility (scope) of a local.

    Note

    In C++ you can also declare statics ('globals') without linkage by enclosing them inside an anonymous namespace. This trick is used commonly in header-only libraries:

    namespace /*anon*/
    {
        void foo() {}    // only in this translation unit
        int answer = 42; // this too
    }
    

    What happens if I use extern?

    If you use extern, the declaration is an extern declaration only (nothing is defined). As such, it normally would be expected to external linkage by definition - being defined in another translation unit. (So it acts the same as if when it was declared at global scope). This is similar to local function declarations:

    int main()
    {
        void exit(int); // equivalent to non-local declaration
    }
    

    Note that, in your 2. example, variable i was already declared static and it will therefore not get external linkage. I might get declared in another translation unit without linker conflicts, though.

提交回复
热议问题