View Single Post
Old Nov 13th, 2005, 11:44 AM   #7
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Dry west coast of Canada
Posts: 1,033
Rep Power: 5 lectricpharaoh will become famous soon enough
Rather than defining your variables in your header, define them in a C or C++ source file, outside of all functions. You can initialize them in this file. Do not declare them with the static keyword, as this will limit their visibility to this single source file. Then, in your header file, simply declare them, using the extern keyword. This tells the compiler that the variables are defined elsewhere, but allows the declaration to be in scope so you don't get an undefined symbol error.

To paraphrase, use this in your source file:
long count = 0;
int errorCode = 0;
And use this in your header file:
extern long count; 
extern int errorCode;
The reason you do it like this is to a) avoid multiple definitions of the same symbol within the same scope, and b) allow you to compile your source file that defines these variables into an object file (possibly adding it to a library), and use it without receiving 'undefined symbol' errors.

The trick here is to realize the difference between a 'definition' and a 'declaration'. A declaration merely declares something, so the compiler knows of its existence and what type it is. This applies to functions as well as variables. For example, a prototype is a declaration. The sole purpose of this is to allow the compiler to perform proper error checking (such as issuing a warning or error when you assign a long to a short, or call a function with the incorrect number or type of arguments) and possibly some optimizations (the more information the compiler has, the better it can do its job). A definition, on the other hand, actually creates an instance and allocates storage (for variables) or contains the code body (for functions). Note that a definition is essentially a stronger form of a declaration; in other words, every definition is a declaration as well, but not every declaration is a definition.
__________________
And once again, Probability proves itself willing to sneak into a back alley and service Drama as would a copper-piece harlot.
- Vaarsuvius, Order of the Stick
lectricpharaoh is offline   Reply With Quote