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?

  • 6
    When you need the benefits that an extern provides, and those benefits outweigh the costs. – Robert Harvey Dec 2 '17 at 17:28
  • 2
    Note that your question is an exact duplicate of this question on Stack Overflow. – Robert Harvey Dec 2 '17 at 17:29
  • std::cout as one example. I'd hate to have to initialize a console object every time I wanted to output something in a quick test project. – user204677 Dec 8 '17 at 3:55

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)

Your Answer

