title: C++: implementing a global constant whose value is given by the user
body: <p>First of all, let me say I have read similar threads on how to initialize a global variable or how to properly implement global constants. Nevertheless, these questions did not really help me with my concrete problem, as also haven't any other ressources I've consulted. The problem is the following.</p>
  
  <p>I (have to) declare in a header file header.h a variable that must be constant and used by the main function in main.cpp as well as other functions defined in a another file functions.cpp (that are previously declared in header.h). The problem is this constant is a runtime constant, whose value is given by the user. How should I proceed? </p>
  
  <p>I think my best shot was to do as follows. In header.h</p>
  
  <pre><code>// Header guard
  
  namespace n
  {
      // Some forward declarations
  
      extern const double mu; // The constant that should be initialized by the user.
  
      // Some other declarations
  }
  </code></pre>
  
  <p>then in functions.cpp</p>
  
  <pre><code>#include "header.h"
  
  namespace n
  {
      // Some definitions here
  
      double function_that_uses_mu(double a, double b)
      {
          // Some code using mu
  
          return somedouble;
      }
  
      // Some other definitions
  }
  </code></pre>
  
  <p>finally main.cpp</p>
  
  <pre><code>#include "header.h"
  #include &lt;iostream&gt;
  
  int main()
  {
      // Some code
  
      double value_of_mu{};
      std::cin &gt;&gt; value_of_mu;        
      // Validity check
      extern const double n::mu{ value_of_mu };
  
      // More code
  
      return 0;
  }
  </code></pre>
  
  <p>The problem is that compilation fails due to the fact that <code>error: ‘mu’ has both ‘extern’ and initializer</code>. However, if I tried <code>mu = value_of_mu</code> I would obviously get an error because I would be assigning to a const value (not initialising it). So I don't know how to proceed, or what's wrong with my code. There are two mandatory facts I must respect:</p>
  
  <ol>
  <li><p>Functions/global-consts definitions, functions/global-consts declarations and main must be split in the three aforementioned files.</p></li>
  <li><p>mu is to be defined as a constant shared by all three files.</p></li>
  </ol>
  
  <p>Is this possible? How?</p>
  
  <p>EDIT:</p>
  
  <p>I think my problem is that an exten variable can't be initialised inside a function, but if this is so, I don't see how I do what I'm trying to.</p>