C++ – How to Prevent Global Variables in a Big Project

cclanggccvariables

With 'global variables', I mean

  • Variables on namespace level
  • Static data members in classes
  • Static variables in functions

In a big C++ project I would like to have a mechanism (like a compiler option) to prevent such data in most parts. A compiler error or warning would be nice. Of course, at one point you have to instantiate your classes.

Conceptually we have the notion of "runnables" which is the code encapsulation. While provided by the platform project they can be 'instantiated' and connected by the downstream project. Unfortunately, since usually there was only one instance of a type, devs used a lot of globals or statics. Needless to say this isn't good practise and you run into problems when doing two instances of a class later.

It's ok to have only one build preventing this (we have GCC, Clang, VS and GHS). I guess a linker option isn't applicable as the executable is linked in the downstream project and they instantiate the 'runnables' on namespace level. Another idea would be to search the object (.o) files if they contain something for the data segment, but I'm uncertain how to do that.

Best Answer

Some things can definitely be enforced by the compiler. Some other, unfortunately, cannot.

A good alternative to compiler warnings / errors is using a static analysis tool, configured appropriately according to your desires.

All "automated" solutions must be used as a tool during (the preparation of) a peer review.

As it was already suggested, the problem of global variables is more of a "mentality" problem, not related to syntax or anything. Keep reading about how you can deal with it (most important, using a static analysis tool and peer reviews, based on internal company regulations).


However, all the above will work only once there are some rules implemented at the workplace.

  • There must be some "development process" implemented, specifying things like:
    • how requirements will be written, to which level of detail;
    • how the source code must be written;
    • how everything will be verified and tested.
  • regarding the "how the source code must be written", there must be a coding guideline about it implemented in the company.

There are many coding guidelines available, some of them freely available, some for some fee. You will find many of them on the internet. Study them and see what fits best to your environment.

A good starting point is the MISRA coding guidelines. They were created to be used by the automotive industry, so they tend to be very strict. However, they will give a good insight about how to think.

You will also find interesting information (not necessarily regarding global variables) on the PC LINT site. I sometimes "relax" reading the "Bug of the month" section.