Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linkage of symbols within anonymous namespace within a regular namespace

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?
        }
    }
}
like image 205
Alex B Avatar asked Nov 15 '10 02:11

Alex B


1 Answers

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.

like image 64
James McNellis Avatar answered Oct 08 '22 12:10

James McNellis