1

In the following code, this is calling the variables in the globals.cpp namespace actual global variables.

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; } 

I know that extern is used to access global variables in other translation units. I'm probably reading too much into this, but why are the variables in the globals.cpp namespace considered to be global when they have namespace scope? Also, am I right to assume that Constants::pi retrieves the identifier pi from the forward declaration in the globals.h namespace?

This question is a continuation of a previous question that I asked here.

0

1 Answer 1

5

Global roughly means accessible from every translation unit, no matter if the variable is in a namespace or not. The best example is std::cout, which is a global variable defined in namespace std, and which represents an instantiation of std::basic_ostream<>.

Regarding your second question, Constants::pi is accessible because you include the header globals.h, which declares extern const double Constants::pi;. This declaration instructs the compiler that the variable has external linkage, and it is your responsibility to define it in some .cpp file (which you do in globals.cpp)1). So the linker is able to find the symbol in the globals.cpp, and that's it.


1) Note that you can even provide the definition extern const double pi = 3.14; directly in the header file, but it is not recommended, since including the header in multiple translation units will lead to a duplicate symbol.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! The world makes more sense now in my mind.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.