devxlogo

Correctly Declaring Global Objects

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.

See also  Is Machine Learning Automating Creativity in Graphic Design?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist