static vs non-static variables in namespace

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

提交回复
热议问题