title: Linkage of static variables in member functions defined in-class
body: <pre><code>//lib.h
  #pragma once
  #ifdef _MSC_VER
  #ifdef BUILD_LIB
  #define LIB_API __declspec(dllexport)
  #else 
  #define LIB_API __declspec(dllimport) /* here */
  #endif
  #else
  #define LIB_API
  #endif
  
  void LIB_API boo();
  
  class LIB_API foo {
  public:
      int bar() {
          static int a = 0;
          return a++;
      }
  };
  
  //lib.cpp
  #include &quot;lib.h&quot;
  
  void boo() {
      foo f;
      f.bar();
  }
  
  // main.cpp
  #include &lt;cstdio&gt;
  #include &quot;lib.h&quot;
  
  int main(int argc, char** argv) {
      foo f;
      boo();
      printf(&quot;%d\n&quot;, f.bar());
      return 0;
  }
  </code></pre>
  <p>For MSVC, without __declspec(dllimport) it appears the variable has multiple instances - the output is 0. Otherwise the output is 1.</p>
  <p>When foo::bar is defined in lib.cpp, even without __declspec(dllimport), the output is 1.</p>
  <p>I'm not familiar with how other compilers handle exporting and importing symbols, but by default with:</p>
  <pre><code>g++ -shared lib.cpp -o lib.so
  g++ main.cpp -L . lib.so
  ./a.out
  </code></pre>
  <p>The output is 1.</p>
  <p>Is it possible that with certain options, g++ will behave like MSVC, that is, producing multiple instances of a?</p>
  <p>Does the standard say anything about how functions defined in-class shall be instantiated, and does it have anything to do with how compilers handle static variables declared inside?</p>
  <hr />
  <p><a href="https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables" rel="nofollow noreferrer">cppreference</a> says:</p>
  <blockquote>
  <p>Function-local static objects in all definitions of the same inline
  function (which may be implicitly inline) all refer to the same object
  defined in one translation unit.</p>
  </blockquote>
  <p>I guess it's not otherwise guaranteed whatsoever.</p>