title: How to declare a variable as thread local portably?
body: <p>C11 introduces the <code>_Thread_local</code> storage class specifier that can be used in combination with the <code>static</code> and <code>extern</code> storage class specifiers to declare a variable as thread local. The GNU C compiler suite implements a storage class specifier <code>__thread</code> with the same same semantics.</p>
  <p>Unfortunately I did not find any compiler (I tried gcc, clang and SUN studio) that actually implements the <code>_Thread_local</code> keywords. I currently use the following construct to declare a keyword <code>thread_local</code>:</p>
  <pre><code>/* gcc doesn't know _Thread_local from C11 yet */
  #ifdef __GNUC__
  # define thread_local __thread
  #elif __STDC_VERSION__ &gt;= 201112L
  # define thread_local _Thread_local
  #else
  # error Don't know how to define thread_local
  #endif
  </code></pre>
  <p>I know that this probably does not work with MSVC and other compilers. Can anybody suggest me a better method to declare <code>thread_local</code> in a way that it works in as many compilers as possible?</p>
  <h2>Edit</h2>
  <p><a href="https://stackoverflow.com/users/48015/christoph">Christoph</a> suggested that Microsoft Visual C allows <code>__declspec(thread)</code>. This is the updated macro definition:</p>
  <pre><code>/* gcc doesn't know _Thread_local from C11 yet */
  #ifdef __GNUC__
  # define thread_local __thread
  #elif __STDC_VERSION__ &gt;= 201112L
  # define thread_local _Thread_local
  #elif defined(_MSC_VER)
  # define thread_local __declspec(thread)
  #else
  # error Cannot define thread_local
  #endif
  </code></pre>