Friday, Jan 19th

Last update12:59:40 PM GMT

What are the different types of linkages?

Write e-mail

Linkage is used to determine how the same name declared in different scopes can refer to the same thing. An object has one name, but in many cases the programmer would like to be able to refer to the same object from different scopes. A typical example would be 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 types, 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 used in a program (except as the operand of a sizeof operator) must have 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 <stdio.h>

// 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);

Share this post

Web Hosting