Global variables

suggest change

To declare a single instance of a variable which is accessible in different source files, declare it at namespace scope with extern. That tells the compiler that a definition exists somewhere else, so every use refers to the same object.

// 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;
}
The radius is: 123

Feedback about page:

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



Table Of Contents