Game Engine Architecture

(Ben Green) #1

112 3. Fundamentals of Software Engineering for Games


tion units, the compiler will not be able to identify the problem, because
it operates on one translation unit at a time. But in this case, the linker
will give us a “multiply defi ned symbol” error when it tries to resolve the
cross-references.

Defi nitions in Header Files and Inlining
It is usually dangerous to place defi nitions in header fi les. The reason for this
should be prett y obvious: If a header fi le containing a defi nition is #included
into more than one .cpp fi le, it’s a sure-fi re way of generating a “multiply de-
fi ned symbol” linker error.
Inline function defi nitions are an exception to this rule, because each in-
vocation of an inline function gives rise to a brand new copy of that function’s
machine code, embedded directly into the calling function. In fact, inline func-
tion defi nitions must be placed in header fi les if they are to be used in more
than one translation unit. Note that it is not suffi cient to tag a function declara-
tion with the inline keyword in a .h fi le and then place the body of that func-
tion in a .cpp fi le. The compiler must be able to “see” the body of the function
in order to inline it. For example:
foo.h
// This function definition will be inlined properly.
inline int max(int a, int b)
{
return (a > b)? a : b;
}
// This declaration cannot be inlined because the
// compiler cannot “see” the body of the function.
inline int min(int a, int b);

foo.cpp
// The body of min() is effectively “hidden” from the
// compiler, and so it can ONLY be inlined within
// foo.cpp.
int min(int a, int b)
{
return (a <= b)? a : b;
}

The inline keyword is really just a hint to the compiler. It does a cost/
benefi t analysis of each inline function, weighing the size of the function’s
code versus the potential performance benefi ts of inling it, and the compiler
gets the fi nal say as to whether the function will really be inlined or not. Some
compilers provide syntax like __forceinline, allowing the programmer
Free download pdf