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

Categories

In C++, putting a function or a variable in an anonymous namespace makes its linkage internal, i. e. the same as declaring it static on a file-level, but idiomatic C++.

What about an anonymous namespace within a normal namespace? Does it still guarantee internal linkage?

// foo.cpp

void func1() {
    // external linkage
}

static void func2() {
    // internal linkage
}

namespace {
    void func3() {
        // internal linkage
    }
}

namespace ns1 {
    void func4() {
        // external linkage
    }

    namespace {
        void func3() {
            // still internal linkage?
        }
    }
}
See Question&Answers more detail:os

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

1 Answer

It's not necessarily the case that entities in an anonymous namespace have internal linkage; they may actually have external linkage.

Since the unnamed namespace has a name that is unique to the translation unit in which it was compiled, you just can't refer to the entities declared in it from outside of that translation unit, regardless of what their linkage is.

The C++ standard says (C++03 7.3.1.1/note 82):

Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name unique to their translation unit and therefore can never be seen from any other translation unit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...