title: Static global variable used by inline member function
body: <p>When you have a static global variable in a C++ header file, each translation unit that includes the header file ends up with its own copy of the variable.</p>
  
  <p>However, if I declare a class in that same header file, and create a member function of that class, implemented inline within the class declaration, that uses the static global variable, for example:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  static int n = 10;
  
  class Foo {
   public:
     void print() { std::cout &lt;&lt; n &lt;&lt; std::endl; }
  };
  </code></pre>
  
  <p>then I see slightly odd behavior under gcc 4.4:</p>
  
  <ol>
  <li><p>If I compile without optimization, all uses of the member function use the copy of the variable from one of the translation units (the first one mentioned on the g++ command line).</p></li>
  <li><p>If I compile with <code>-O2</code>, each use of the member function uses the copy of the variable from the translation unit in which the case is made.</p></li>
  </ol>
  
  <p>Obviously this is really bad design, so this question is just out of curiosity.  But my question, nonetheless, is what does the C++ standard say about this case?  Is g++ behaving correctly by giving different behavior with and without optimization enabled?</p>