<html>
    <head>
      <base href="https://bugs.llvm.org/">
    </head>
    <body><table border="1" cellspacing="0" cellpadding="8">
        <tr>
          <th>Bug ID</th>
          <td><a class="bz_bug_link 
          bz_status_NEW "
   title="NEW - function static variable instantiated at -O2 despite extern template"
   href="https://bugs.llvm.org/show_bug.cgi?id=45351">45351</a>
          </td>
        </tr>

        <tr>
          <th>Summary</th>
          <td>function static variable instantiated at -O2 despite extern template
          </td>
        </tr>

        <tr>
          <th>Product</th>
          <td>clang
          </td>
        </tr>

        <tr>
          <th>Version</th>
          <td>trunk
          </td>
        </tr>

        <tr>
          <th>Hardware</th>
          <td>PC
          </td>
        </tr>

        <tr>
          <th>OS</th>
          <td>Windows NT
          </td>
        </tr>

        <tr>
          <th>Status</th>
          <td>NEW
          </td>
        </tr>

        <tr>
          <th>Severity</th>
          <td>normal
          </td>
        </tr>

        <tr>
          <th>Priority</th>
          <td>P
          </td>
        </tr>

        <tr>
          <th>Component</th>
          <td>LLVM Codegen
          </td>
        </tr>

        <tr>
          <th>Assignee</th>
          <td>unassignedclangbugs@nondot.org
          </td>
        </tr>

        <tr>
          <th>Reporter</th>
          <td>sbence92@gmail.com
          </td>
        </tr>

        <tr>
          <th>CC</th>
          <td>llvm-bugs@lists.llvm.org, neeilans@live.com, richard-llvm@metafoo.co.uk
          </td>
        </tr></table>
      <p>
        <div>
        <pre>Created <span class=""><a href="attachment.cgi?id=23291" name="attach_23291" title="example">attachment 23291</a> <a href="attachment.cgi?id=23291&action=edit" title="example">[details]</a></span>
example

In the below example func is inlined and function_local_static becomes a
defined symbol when compiled with -O2 and above regardless of extern template
class declaration.

The problem is solved by adding -fno-inline .
Same can be observed with clang above 5.0 (works with 4.0.1), all gcc versions
(bugzilla ID 92359), icc, but not with msvc.

This is problematic when one tries to rely on the extern template mechanism in
shared libraries. The result is that function static variables get instantiated
more than 1 times.
Attached you find a minimal example showing exactly this.

minimal example that shows function_local_static being defined at -O2:

template <typename T>
struct S {
  int func() {
    static int function_local_static = 0;
    return ++function_local_static;
  }
};

extern template class S<int>;

int user()
{
    return S<int>().func();
}</pre>
        </div>
      </p>


      <hr>
      <span>You are receiving this mail because:</span>

      <ul>
          <li>You are on the CC list for the bug.</li>
      </ul>
    </body>
</html>