static vs non-static variables in namespace

前端 未结 4 1149
余生分开走
余生分开走 2020-12-04 23:54

I have a namespace foo which contains an integer bar, declared so...

foo.h:

namespace foo {
    int bar;
}
<
4条回答
  •  情歌与酒
    2020-12-05 00:11

    There are multiple meanings for static in different contexts. In this particular context it means that the variable has internal linkage, and thus each translation unit that includes that header will have it's own copy of the variable.

    Note that while this will silent the linker error, it will do so maintaining a separate foo::bar variable for each one of the object files generated (changes will not be visible across different object files).

    If you want a single variable, you should declare it as extern in the header and provide a single definition in one translation unit.

提交回复
热议问题