• RSS
  • Facebook
  • Twitter

Knowledge is Power.

  • Who you are ?

    Working on machines without understanding them ? Then you should be here..

  • Where you are ?

    Geographical location should not become a barrier to Share our knowledge.

  • What do you do ?

    Puzzles and Interview question are intended to be discussed here.

    Sunday, March 28, 2010

    Linkage is used to determine what makes the same name declared in different scopes refer to the same thing. An object only ever has one name, but in many cases we would like to be able to refer to the same object from different scopes. A typical example is the wish to be able to call printf() from several different places in a program, even if those places are not all in the same source file.

    The Standard warns that declarations which refer to the same thing must all have compatible type, or the behaviour of the program will be undefined. Except for the use of the storage class specifier, the declarations must be identical.


    The three different types of linkage are:


    * external linkage
    * internal linkage
    * no linkage



    In an entire program, built up perhaps from a number of source files and libraries, if a name has external linkage, then every instance of a that name refers to the same object throughout the program. For something which has internal linkage, it is only within a given source code file that instances of the same name will refer to the same thing. Finally, names with no linkage refer to separate things.

    Linkage and definitions

    Every data object or function that is actually used in a program (except as the operand of a sizeof operator) must have one and only one corresponding definition. This "exactly one" rule means that for objects with external linkage there must be exactly one definition in the whole program; for things with internal linkage (confined to one source code file) there must be exactly one definition in the file where it is declared; for things with no linkage, whose declaration is always a definition, there is exactly one definition as well.


    The three types of accessibility that you will want of data objects or functions are:


    * Throughout the entire program,
    * Restricted to one source file,
    * Restricted to one function (or perhaps a single compound statement).



    For the three cases above, you will want external linkage, internal linkage, and no linkage respectively. The external linkage declarations would be prefixed with extern, the internal linkage declarations with static.



    #include

    // External linkage.
    extern int var1;

    // Definitions with external linkage.
    extern int var2 = 0;

    // Internal linkage:
    static int var3;

    // Function with external linkage
    void f1(int a){}

    // Function can only be invoked by name from within this file.
    static int f2(int a1, int a2)
    {
    return(a1 * a2);
    }

    0 comments:

    Post a Comment