Linkage

Linkage refers to the visibility of an object inside other files. There are three types of linkage: external linkage, internal linkage and no linkage. We have no linkage with local scope objects (variables, classes, etc.). We have internal linkage when our objects, although global, can only be seen inside the file they’re defined. In an external linkage, the objects are visible in any other file. Examples of objects that are externally linked: regular functions, global variables, classes and namespaces (when properly qualified). Examples of objects that are internally linked: static functions and members of anonymous namespaces (this is the case because we can’t properly qualify a namespace that has no name).

Here’s an example of external linkages.

//external.hpp
extern int x; 
void func(int y);

namespace my_namespace {
    extern int x;
}

class my_class {
public:
    int x;
    void func(int y);
};
//external.cpp
#include "external.hpp"

int x;

void func(int y){
    x = y;
}

int my_namespace::x = 3;

void my_class::func(int y){
    my_class::x = y;
}
//main.cpp
#include "internal.hpp"

#include <cstdio>

int main(){
    func(4);
    printf("%d\n", x);
    printf("%d\n", my_namespace::x);

    my_class mc;
    mc.func(9);
    printf("%d\n", mc.x);
    return 0;
}

Here’s an example of internal linkages.

//internal.hpp
extern int x; 
static void func(int y);
namespace {
    void func2(int y);
}
void func3(int y);
//internal.cpp
#include "internal.hpp"

int x;

static void func(int y){
    x = y;
}
void func2(int y){
    x = y;
}
void func3(int y){
    x = y;
}
//main.cpp
#include "internal.hpp"
#include <cstdio>

int main(){
    //func(11);  //error
    //func2(12); //error
    func3(13);
    printf("%d\n", x);
    return 0;
}

When using the namespace without defining a name, for internal.cpp file, it’s the same effect of declaring a global function. But for external files, it is required to explicit the namespace name. Since we do not know it, the behavior of functions declared inside an anonymous namespace is the same as the static function. By the way, using static modifier to hide functions from external access is deprecated. One should use anonymous namespace.

Further reading

On C++ Namespaces – http://winterdom.com/dev/cpp/nspaces
http://stackoverflow.com/questions/154469/unnamed-anonymous-namespaces-vs-static-functions
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=41
http://publications.gbdirect.co.uk/c_book/chapter4/linkage.html

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s