static vs non-static variables in namespace

前端 未结 4 1137
余生分开走
余生分开走 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.

    0 讨论(0)
  • 2020-12-05 00:22

    The problem is caused by having more than one definition of the variable. The definitions in different translation units conflict with each other, just like multiple non-inline function definitions wouldn't work.

    When you make the variable static you're giving the variable internal linkage, so each translation unit has its own independent copy.

    What you probably actually want is to put only the declaration in a header (using extern) and then put the definition in an implementation file.

    0 讨论(0)
  • 2020-12-05 00:23

    Also note that const int at namespace (global) scope in C++ has static implicitly added by default: Define constant variables in C++ header

    To better understand what is going on, do a readelf on the intermediate ELF object files of the compilation, and you will see clearly is symbols are defined twice or not. Here is a detailed example: What does "static" mean in C?

    0 讨论(0)
  • 2020-12-05 00:24

    When you declare a variable as static, it means that its scope is limited to the given translation unit only. Without static the scope is global.

    When you declare a variable as static inside a .h file (within or without namespace; doesn't matter), and include that header file in various .cpp files, the static variable becomes locally scoped to each of the .cpp files.
    So now, every .cpp file that includes that header will have its own copy of that variable.

    Without the static keyword the compiler will generate only one copy of that variable, so as soon as you include the header file in multiple .cpp files the linker will complain about multiple definitions.

    0 讨论(0)
提交回复
热议问题