How does extern work in namespaces?

I am running a simple program similar to what I found here . This meant reducing code bloat when including constants in multiple files. It does this using const global variables in the namespace with corresponding externforward declarations .

globals.h

#ifndef GLOBALS_H_
#define GLOBALS_H_

namespace Constants
{
    // forward declarations only
    extern const double pi;
    extern const double avogadro;
    extern const double my_gravity;
}

#endif

globals.cpp

namespace Constants
{
    // actual global variables
    extern const double pi(3.14159);
    extern const double avogadro(6.0221413e23);
    extern const double my_gravity(9.2); // m/s^2 -- gravity is light on this planet
}

source.cpp

#include <iostream>
#include <limits>

#include "globals.h"

int main()
{
    double value_of_pi = Constants::pi;

    std::cout << value_of_pi;

    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cin.get();

    return 0;
}

, Constants:: pi pi, globals.cpp Constants, , globals.h. , / const global globals.cpp extern? extern globals.cpp, , , . , extern ? const /? , ?

+4
1

, , : ( ".cpp files" ), . const, , - One Definition.

extern globals.cpp, , ,

, namespace-scope const (, pi) , extern.

, extern ?

extern , ( ".cpp file" ). const, , , extern, ( , const).

, ?

, const [basic.link]/3 ++:

, (3.3.6), ,

(3.1) [...] - , , ; ,

(3.2) - , ;

(3.3) - .

+8

All Articles