title: How to correctly define constants in C++
body: <p>I see a common pattern in many C++ codebases:</p>
  
  <p>Header.h:</p>
  
  <pre><code>static const int myConstant = 1;
  </code></pre>
  
  <p>Source1.cpp:</p>
  
  <pre><code>#include "Header.h"
  </code></pre>
  
  <p>Source2.cpp:</p>
  
  <pre><code>#include "Header.h"
  </code></pre>
  
  <p>Based on:</p>
  
  <blockquote>
    <p>3.5 Program and linkage</p>
  </blockquote>
  
  <p>...</p>
  
  <blockquote>
    <p>(2.1) — When a name has external linkage , the entity it denotes can be referred to by names from scopes of
    other translation units or from other scopes of the same translation unit.</p>
    
    <p>(2.2) — When a name has internal linkage , the entity it denotes can be referred to by names from other scopes
    in the same translation unit.</p>
  </blockquote>
  
  <p>...</p>
  
  <blockquote>
    <p>3 A name having namespace scope (3.3.6) has internal linkage if it is the name of</p>
    
    <p>(3.1) — a variable, function or function template that is explicitly declared static; or,</p>
  </blockquote>
  
  <p><code>myConstant</code> is accessible only from the same translation unit and the compiler will generate multiple instances of it, one for each translation unit that included <code>Header.h</code>. </p>
  
  <p>Is my understanding correct - multiple instances of <code>myConstant</code> are created? If this is the case can you please point me to better alternatives of using constants in C++</p>
  
  <p>EDIT:</p>
  
  <p>Some suggested to make <code>myConstant</code> <code>extern</code> in the header and define it in one <code>cpp</code> file. Is this a good practice? I <strong>guess</strong> this will make the value invisible to the compiler and prevent many optimizations, for example when the value appears in arithmetic operations.</p>