Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Jan 3, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.cpp
int 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.

Danny Kalev
Thanks for your registration, follow us on our social networks to keep up-to-date