@kaeota: before anyone says, "DONT USE GLOBALS BECAUSE..." |
There's nothing wrong with global
constants. You shouldn't confuse
constants with
variables. You should try to avoid using global
variables.
@Robo: I suggest moving your COMMAND_COUNT global to your validate.h file |
That's right! The other option is to move it to a new file, called e.g.
definitions.h, and include this in both files.
@Grey Wolf: Read up on the extern keyword |
The
extern
keyword is for
variables, not
constants.
The reason you need it for variables, is that if you declare
int foo
in a header file, and include it in two
compilation units (which basically means two cpp files), it won't link because of "duplicate reference to foo". The way around this is to declare
extern int foo
in a header file, and
int foo
in one of the cpp files. This way the
variable can be accessed from anywhere.
On the other hand,
constants doesn't cause this problem. You can declare
const int FOO = 10
in a header file, and include it everywhere. When the compiler sees the constant in an expression, it inserts the value "inline" instead of a reference to a memory location where it is stored.
More technically: When using constants the compiler doesn't need to create labels in the object file, like it must for variables. The
extern
keyword means that there is some value in another compilation unit stored in a location labeled by the name. This is of course different from how constants are supposed to be used. Like I said, you should never declare something
extern const ...
.
EDIT:
With "you should never", I really mean that you shouldn't use it in this and similar contexts. There are contexts where it might be useful: If the data type has a complex constructor, or internal state (i.e. if it's not a built-in type), or if the value of the constant is "unknown" or implementation specific -- not available in the header file.