Under which circumstances would you deem it justifiable to use externs (i.e. global variables)?
For example, in a system with 1 given state at a time, would it be appropriate to store this state in an extern?
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
You may need an
extern global variable, if:
an element of the program's state (i.e. the global variable content) needs to be shared, AND
it is not possible to manage these elements as a static class member (by preference a private or protected one), AND
it is not possible to afford the overhead of encapsulating it into a singleton, AND
there's no easy way to make the objects/function that deal with that state to know each other and communicate directly instead of using the global, AND
it is not desirable to regroup the classes/functions that need this state into the same compilation unit (which could at least reduce the risk of unexpected side effects, by making that global variable
static and thus less visible).
Alternatively, you might need an
extern volatile global variable for the same reasons, but if it's about the system state (e.g. fixed location used by hardware)