Home > OS >  Global function call from function in unnamed namespace with the same name
Global function call from function in unnamed namespace with the same name

Time:05-26

I have a some code. file1.cpp:

extern void callout();

int answer() {
    return 5;
}

int main(){
    callout();

    return 0;
}

file2.cpp

#include <iostream>

using std::cout; using std::endl;

namespace {
    int answer() {
        cout << ::answer() << endl;
        return 12;
    }
}

void callout() {
    cout << answer() << endl;
}

Instead of calling the global answer() function, the answer() function in unnamed namespace is calls itself recursively, resulting in a stack overflow. How do I call the global answer() function from answer() function in unnamed namespace?

CodePudding user response:

First of all, if you want to call a function, it needs to be declared in the translation unit. The answer function from file1.cpp is currently not declared in file2.cpp's translation unit.

To fix this add a header file included in both .cpp files containing

int answer();

(By the way: extern on a function declaration is pretty much useless)

With this, the qualified call ::answer() should work as you want it to, calling the overload in the global namespace.

Unfortunately, as you noted in the comments, it will result in the unqualified call answer() in callout failing. This is because an unnamed namespace behaves as if the using namespace /* unnamed namespace name */; was used and unqualified name lookup will consider both the overload in a namespace as well as the overload introduced "as if" part of the namespace due to a using-directive equally.

I don't think there is any way to call the answer inside the unnamed namespace from outside of it under these circumstances. You can't differentiate the functions by overload resolution and you can't select the one inside the unnamed namespace by name, since the unnamed namespace doesn't have a name you can refer to. Your best option is to rename answer in file2.cpp or to add a function in the unnamed namespace with a different name forwarding the call to answer. Inside the unnamed namespace a simple unqualified call answer() will call the function in the unnamed namespace and will not consider the global namespace scope.

All of this would be easier if you didn't use (only) an unnamed namespace. If there was a named namespace differentiating the two functions, either could be called by qualified name.

  •  Tags:  
  • c
  • Related