Game Engine Architecture

(Ben Green) #1

114 3. Fundamentals of Software Engineering for Games


// This ‘gInternalVariable’ is distinct from the one
// defined in foo.cpp – no error. We could just as
// well have named it gInternalVariableForBarCpp – the
// net effect is the same.
static U32 gInternalVariable;

// This function is distinct from foo.cpp’s
// version – no error. It acts as if we had named it
// internalFunctionForBarCpp().
static void internalFunction()
{
// ...
}

// ERROR – multiply defined symbol!
void externalFunction()
{
// ...
}

Technically speaking, declarations don’t have a linkage property at all, be-
cause they do not allocate any storage in the executable image; therefore, there
is no question as to whether or not the linker should be permitt ed to cross-
reference that storage. A declaration is merely a reference to an entity defi ned
elsewhere. However, it is sometimes convenient to speak about declarations
as having internal linkage, because a declaration only applies to the transla-
tion unit in which it appears. If we allow ourselves to loosen our terminology
in this manner, then declarations always have internal linkage—there is no
way to cross-reference a single declaration in multiple .cpp fi les. (If we put a
declaration in a header fi le, then multiple .cpp fi les can “see” that declaration,
but they are in eff ect each gett ing a distinct copy of the declaration, and each
copy has internal linkage within that translation unit.)
This leads us to the real reason why inline function defi nitions are permit-
ted in header fi les: It is because inline functions have internal linkage by de-
fault, just as if they had been declared static. If multiple .cpp fi les #include
a header containing an inline function defi nition, each translation unit gets a
private copy of that function’s body, and no “multiply defi ned symbol” errors
are generated. The linker sees each copy as a distinct entity.

3.2.3. C/C++ Memory Layout

A program writt en in C or C++ stores its data in a number of diff erent places in
memory. In order to understand how storage is allocated and how the various
Free download pdf