110 3. Fundamentals of Software Engineering for Games
The compiler only operates on one translation unit at a time, so whenever
it encounters a reference to an external global variable or function, it must
“go on faith” and assume that the entity in question really exists, as shown
in Figure 3.7. It is the linker’s job to combine all of the object fi les into a fi nal
executable image. In doing so, the linker reads all of the object fi les and at-
tempts to resolve all of the unresolved cross-references between them. If it is
successful, an executable image is generated containing all of the functions,
global variables, and static variables, with all cross-translation-unit references
properly resolved. This is depicted in Figure 3.8.
The linker’s primary job is to resolve external references, and in this ca-
pacity it can generate only two kinds of errors:
- The target of an extern reference might not be found, in which case the
linker generates an “unresolved symbol” error. - The linker might fi nd more than one variable or function with the same
name, in which case it generates a “multiply defi ned symbol” error.
These two situations are shown in Figure 3.9.
3.2.2.2. Declaration versus Defi nition
In the C and C++ languages, variables and functions must be declared and de-
fi ned before they can be used. It is important to understand the diff erence be-
tween a declaration and a defi nition in C and C++.
z A declaration is a description of a data object or function. It provides the
compiler with the name of the entity and its data type or function signature
(i.e., return type and argument type(s)).
z A defi nition, on the other hand, describes a unique region of memory in
the program. This memory might contain a variable, an instance of a
struct or class, or the machine code of a function.
In other words, a declaration is a reference to an entity, while a defi nition is the
entity itself. A defi nition is always a declaration, but the reverse is not always
the case—it is possible to write a pure declaration in C and C++ that is not a
defi nition.
Functions are defi ned by writing the body of the function immediately af-
ter the signature, enclosed in curly braces:
foo.cpp
// definition of the max() function
int max(int a, int b)
{