I want to understand the external linkage and internal linkage and their difference.
I also want to know the meaning of
const
va
extern
declaration in the other file.static
. Such variables are said to have internal linkage.Consider following example:
void f(int i);
extern const int max = 10;
int n = 0;
int main()
{
int a;
//...
f(a);
//...
f(a);
//...
}
f
declares f
as a function with external linkage (default). Its definition must be provided later in this file or in other translation unit (given below).max
is defined as an integer constant. The default linkage for constants is internal. Its linkage is changed to external with the keyword extern
. So now max
can be accessed in other files. n
is defined as an integer variable. The default linkage for variables defined outside function bodies is external.#include
using namespace std;
extern const int max;
extern int n;
static float z = 0.0;
void f(int i)
{
static int nCall = 0;
int a;
//...
nCall++;
n++;
//...
a = max * z;
//...
cout << "f() called " << nCall << " times." << endl;
}
max
is declared to have external linkage. A matching definition for max
(with external linkage) must appear in some file. (As in 1.cpp)n
is declared to have external linkage.z
is defined as a global variable with internal linkage.nCall
specifies nCall
to be a variable that retains its value across calls to function f()
. Unlike local variables with the default auto storage class, nCall
will be initialized only once at the start of the program and not once for each invocation of f()
. The storage class specifier static
affects the lifetime of the local variable and not its scope.NB: The keyword static
plays a double role. When used in the definitions of global variables, it specifies internal linkage. When used in the definitions of the local variables, it specifies that the lifetime of the variable is going to be the duration of the program instead of being the duration of the function.
Hope that helps!