Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

c++ - static vs non-static variables in namespace

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

foo.h:

namespace foo {
    int bar;
}

Now if I include foo.h in only one file, this works just fine. But a problem arises when I include foo.h from two or more files: I get a linker error. I figured out that if I declare bar as static, I can include foo.h in more than one file. This seems strange to me, because I wasn't aware that one could declare a static variable inside of a namespace. (what does that even mean?)

Why does this work? And more importantly, why doesn't it work without static? What does static mean when used in a namespace?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...