DeiDei DeiDei - 2 months ago 10
C++ Question

Is there a way to insert a global name into a namespace and made it available only from that namespace?

Let's say I have a function with

"C"
linkage in global scope.

extern "C" int fun(int);


Then if I want to make it visible in a namespace I would do:

namespace foo {
using ::fun;
}


But after this I am still able to call it as
::fun(0)
in addition to
foo::fun(0)
.

So my question is, is there a way to disallow the call from the global namespace for function
fun
and only allow it to be called from
namespace foo
?

Answer

Since the C language does not have namespaces, part of the extern "C" specifier indicates that the source name has no namespace.

Thus the following code would invoke the C function foo:

namespace bar
{
    extern "C" void foo();
}

void foo() {}  // note: legal, so no pre-existing ::foo()

void caller() {
    bar::foo();  // calls the C function
}

So you could just do

namespace bar
{
    extern "C"
    {
        #include "foo.h"
    }
}

or if you need to share it with the C code:

#ifdef __cplusplus
namespace bar
{
    extern "C"
    {
#endif
// .. C-compatible definitions etc
#ifdef __cplusplus
    }
}
#endif
Comments