Global variables

suggest change

To declare a single instance of a variable which is accessible in different source files, it is possible to make it in the global scope with keyword extern. This keyword says the compiler that somewhere in the code there is a definition for this variable, so it can be used everywhere and all write/read will be done in one place of memory.

// File my_globals.h:

#ifndef __MY_GLOBALS_H__
#define __MY_GLOBALS_H__

extern int circle_radius; // Promise to the compiler that circle_radius 
                          // will be defined somewhere

#endif
// File foo1.cpp:

#include "my_globals.h"

int circle_radius = 123; // Defining the extern variable
// File main.cpp:

#include "my_globals.h"
#include <iostream>

int main()
{
    std::cout << "The radius is: " << circle_radius << "\n";'
    return 0;
}

Output:

The radius is: 123

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Scopes:
* Scopes
* Global variables

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype