Javran
Javran

Reputation: 3434

something about C++ unnamed namespace

#include <iostream>

namespace
{
        int a=1;
}

int a=2,b=3;

int main(void)
{
        std::cout<<::a<<::b;
        return 0;
}

I complie it with my g++,but the output is 23, who can explain it? is that a way to get access to the <unnamed> namespace ::a?

Upvotes: 3

Views: 597

Answers (4)

Siddiqui
Siddiqui

Reputation: 7840

You can access the global namespace, but don't redefine it.

#include <iostream>

namespace
{
        int a=1;
}


int b=3;

int main(void)
{
        std::cout<<::a<<::b;
    return 0;
}

here the out is 13.

Upvotes: 0

Viktor Sehr
Viktor Sehr

Reputation: 13099

:: in ::a refers to the global namespace. Anonymous namespace should be accessed via just a (or to be more specific, you shouldn't do like this at all)

Upvotes: 3

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

No, you can't. You can work around it thus:

namespace
{
    namespace xxx
    {
        int a = 1;
    }
}
...
std::cout << xxx::a << ::b;

Upvotes: 3

bdhar
bdhar

Reputation: 22983

Using unnamed namespaces, this is not possible. Refer the below article

http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/unnamed_namespaces.htm

You have to go for named namespaces.

Upvotes: 2

Related Questions