views:

253

answers:

2

What is the impact of namespaces in c++ linkages compared to linkages in c?

Is it possible to make a name that has internal linkage to external linkage just by using namespace.Similarly the other way around.

+3  A: 

In general, namespace name is prepended to any enclosed entity's name before the name is mangled and goes to the linker.

If you have two functions with the same signatures in different namespaces they link into one file just fine. If you have two classes with the same name and at least one method with the same signature and these classes are in different namespaces – they again link together just fine.

sharptooth
+1  A: 

Both C and C++ allow objects and functions to have static file linkage, also known as internal linkage. C++, supports the use of unnamed namespaces instead for file scope, which is a compiler benefit. static is a linkage modifier. So, if you want file scope and internal linkage, you should use both namespace and static in C++. In C, however, you only need static keyword to achieve the same.

/* C and C++ code */

static int  bufsize = 1024;
static int  counter = 0;

static long square(long x)
{
    return (x * x);
}

The preferred way of doing this in C++:

 // C++ code
namespace /*unnamed*/
{
    static int  bufsize = 1024;
    static int  counter = 0;

    static long square(long x)
    {
        return (x * x);
    } 

}
alvatar
Actually, it's only static objects (not functions) that are deprecated. See the C++ standard, Appendix D, section D.2;
anon
Yes, there it states "objects" only. In C++ linkage is internal for both objects and functions and if either unnamed spaces or static linkage is used.
alvatar