Say I'm simulating food for a population:
Eat.cpp:
void eat()
{
food--:
}
Hunt.cpp:
void hunt()
{
food++;
}
eat()
and hunt()
both depend on the integer food
. But my population simulator might include both, one, or neither of these files. How do I ensure that food
only exists if something is included that will use it, and will only be declared once if multiple files use it? Currently my best idea is a sort of header guard, e.g.:
#ifndef FOOD
#define FOOD
int food = 10;
#endif
You could define the variable
food
in one central file (even if that file doesn't use it) and then declare itextern
in every other file that uses it. A good optimizer may be able to optimize the variable away if it is never used or referenced. I have never tested it, though.However, this will likely not work if initialization is required. If initialization is required, you will likely want to ensure that the variable is only initialized once. This initialization would have to be done in one file only and would likely prevent the variable from being optimized away, because the variable was used (even if it was only used for initialization).
Therefore, using the preprocessor for conditional compilation, as you have described in your question, would probably be the best option.