Correctly Declaring Global Objects

Although the use of global variables is not recommended in general, sometimes it’s unavoidable. When using a global variable or object, never instantiate it in a header file because the header is usually #included in several separate source files. As a result, the linker will detect multiple instances of the same object and complain about that. Instead, instantiate a global in a single .cpp file. This way you ensure that it’s defined only once, regardless of the number of source files used in the project. All other source and header files in the project that access the global object need to declare it extern. Here is an example:

 // File a.h/*declaration only; x is defined in another source file*/extern int x; struct Counter{  Counter() {++x;}  ~Counter() {--x;}};// File b.cppint x; //definition of a global variable// File main.cpp#include "a.h"int main(){  Counter count;  cout<<"value of x is: "<<x;}

The two source files, b.cpp and main.cpp are compiled separately. At link time, the linker resolves all references to x to the variable defined in b.cpp.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: