Game Development Reference
In-Depth Information
Listing 9-10 introduces the extern keyword. You use extern to tell the compiler that it can search the
global scope for a variable of this name. In this case the variable will be found in the file containing
_tmain . Trying to use extern with fileVariable will cause an unresolved external symbol error when
you try to build. The variable is unresolved because fileVariable has been declared as static ,
which means that it can only be used from within the file where it was declared.
This use of static to limit variables to file scope is deprecated. That means it is still supported but
no longer the recommended method for achieving file scoped variables. A more modern approach
is to use an anonymous namespace . Listing 9-11 alters Listing 9-8 to use an anonymous namespace
instead of a static variable.
Listing 9-11. Anonymous namespaces
#include "stdafx.h"
#include <iostream>
#include "extern.h"
int globalVariable = 0;
namespace
{
int fileVariable = 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
IncrementGlobalCounters();
std::cout << globalVariable << std::endl;
return 0;
}
The anonymous namespace is simply a namespace that is not given a name. Any of the variables,
functions, or classes that you include inside the namespace will be accessible inside the file that
contains the anonymous namespace .
This section should have given you an idea of just how overloaded the static keyword is. The next
section covers the const keyword, which is not quite as overloaded but still confusing.
The const Keyword
A constant in C++ is a variable that cannot be changed. Constants are useful to store values that
you know at compile time, for passing values into methods that you don't want to be able to change,
and for marking methods in classes that should not be allowed to change member variables. I'll
cover these uses in the following sections.
 
Search WWH ::




Custom Search