Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++) extern

 

Keyword to make a variable known over multiple units, but keeping the declaration and initialization local to a file (probably an implementation file (.cpp) )

 

Example

 

In the example below there are two integer globals (note: avoid using global data [0] [1] ). The int x is declared and initialized in unit1.cpp, the int y in declared in unit2.cpp and initialized by the locally unknown int x. To read the values of both integers, two getters are put in the header files.

 

UnitMain.cpp

 

 

#include "Unit1.h"

#include "Unit2.h"

#include <cassert>

 

int main()

{

assert(GetX() == 42);

assert(GetY() == 42);

}

 

 

Unit1.h

 

 

#ifndef Unit1H

#define Unit1H

 

const int GetX();

 

#endif

 

 

Unit1.cpp

 

 

#include "Unit1.h"

 

int x = 42;

 

const int GetX() { return x; }

 

 

Unit2.h

 

 

#ifndef Unit2H

#define Unit2H

 

const int GetY();

 

#endif

 

 

Unit2.cpp

 

 

#include "Unit2.h"

 

extern int x;

 

int y = x; //Seems risky, dependent on module process order

 

const int GetY() { return y; }

 

 

 

 

 

References

[0]          Herb Sutter , Andrei Alexandrescu . C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Item 10: 'Minimize global and shared data'.

[1]          Herb Sutter , Andrei Alexandrescu . C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Item 18: 'Declare variables as locally as possible'.

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.