Given the following header file, if ‘a’ is defined inside the main body, I get a warning “unused variable ‘a'” and linker error “undefined reference to ‘a’.
header.h:
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
extern int* a;
void f()
{
std::cout<<*a <<std::endl;
return;
}
#endif
main.cpp:
#include "header.h"
int main()
{
int* a = new int(10);
f();
}
However, if ‘a’ is defined outside of main(), the program links with no errors and f() works as expected (prints 10). Why is this?
Example:
int* a = new int(10);
int main()
{
f();
}
You need to learn about name binding, which determines how two
declarations of the same name are related. When you define a variable
within a function, its name has no linkage; i.e. the entity it refers to
is distinct from any other entity in the program.
More generally: a declaration (and in this sense, a definition is also a
declaration) associates a symbol with an entity—an object (in
which case, the declaration declares a variable), a function, a
reference, a type or anything else you can declare in C++. Whether
different declarations of the same name associate with the same entity
or not is defined by their linkage. C++ recognizes three
different types of linkage:
external linkage, in which the entity can be referred to by declarations in other transation units,
internal linkage, in which the entity can be referred to by other declarations in the same translation unit,
and no linkage, in which the entity cannot be referred to by any other declaration.
Variables declared at block scope (i.e. local variables) have no
linkage, unless they are explicitly declared
extern(and a localvariable declared
externcannot be a definition). So theint ainmaindeclares (and defines) an entity which is independent of anyother
ain the program. Variables declared in namespace scope haveexternal linkage, unless they are declared
static, in which case theyhave internal linkage; when you define
int aat namespace scope, ithas external linkage, and so refers to the same entity you declared with
extern int ain the header.