(C++) extern
February 24, 2017 · View on GitHub
(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 [1,2]). 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 <cassert> #include "Unit1.h" #include "Unit2.h" int main() { assert(GetX() == 42); assert(GetY() == 42); }
Unit1.h
#ifndef Unit1H #define Unit1H int GetX(); #endif
Unit1.cpp
#include "Unit1.h" int x = 42; int GetX() { return x; }
Unit2.h
#ifndef Unit2H #define Unit2H int GetY(); #endif
Unit2.cpp
#include "Unit2.h" extern int x; int y = x; //Seems risky, dependent on module process order int GetY() { return y; }
References
- 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'
- 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'