title: How does extern work in namespaces?
body: <p>I'm running a simple program similar to what I found <a href="http://www.learncpp.com/cpp-tutorial/42-global-variables/" rel="noreferrer">here</a>. It's meant to reduce code bloat when including constants in multiple files. It does this by using const global variables within a namespace with their respective <code>extern</code> forward declarations.</p>
  
  <p><strong>globals.h</strong></p>
  
  <pre><code>#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
  </code></pre>
  
  <p><strong>globals.cpp</strong></p>
  
  <pre><code>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
  }
  </code></pre>
  
  <p><strong>source.cpp</strong></p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;limits&gt;
  
  #include "globals.h"
  
  int main()
  {
      double value_of_pi = Constants::pi;
  
      std::cout &lt;&lt; value_of_pi;
  
      std::cin.clear();
      std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n');
      std::cin.get();
  
      return 0;
  }
  </code></pre>
  
  <p>I assume that Constants::pi gets the value pi contained in the globals.cpp Constants namespace, and is able to do so because it has access to the namespace itself from the included globals.h. What I don't understand is why the <strong><em>const global definitions/initializations</em></strong> in globals.cpp need the <code>extern</code> keyword? I tried removing the <code>extern</code> keywords in globals.cpp thinking that it wasn't needed, but my program won't run without them. I thought <code>extern</code> was only used for forward declarations? Why are they needed for the <strong><em>const global definitions/initializations</em></strong>? Has it something to do with the namespace they are defined in?</p>