Search code examples
c++namespacesg++unnamed-namespace

Can you have two functions in/outside an unnamed namespace, both with the same name?


There is following code:

#include <iostream>

using namespace std;

namespace
{
    int funkcja()
    {
        cout << "unnamed" << endl;
        return 0;
    }
}

int funkcja()
{
    cout << "global" << endl;
    return 0;
}

int main()
{
    ::funkcja(); //this works, it will call funkcja() from global scope
    funkcja(); //this generates an error 
    return 0;    
}

I use g++. Is there some way to call function from unnamed namespace in such situation? It is possible to call function from global scope using ::function, but how to call function from unnamed namespace? Compiler generates an error:

prog3.cpp: In function ‘int main()’:
prog3.cpp:43:17: error: call of overloaded ‘funkcja()’ is ambiguous
prog3.cpp:32:5: note: candidates are: int funkcja()
prog3.cpp:25:6: note:                 int<unnamed>::funkcja()

Solution

  • Is there some way to call function from unnamed namespace in such situation?
    No, Not in your case.

    Anonymous/UnNamed namespaces allow variables and functions to be visible within an entire translation unit, yet not visible externally. 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.

    This means your function funkcja inside the Unnamed Namespace is visible in the translation unit which defines a global function funkcja. This causes two same named functions defined in the global scope and thus causing the redefinition error.

    If funkcja was only present in your UnNamed Namespace then You would have been able to call it by ::funkcja as it would be in your global scope. To conclude, you can call functions in UnNamed Namespace depending on the scope in which the UnNamed Namespace is present.