c++ thread-local storage clang-503.0.40 (Mac OSX)

落花浮王杯 提交于 2019-12-29 06:39:09

问题


After I declared a variable in this way:

   #include <thread>
   namespace thread_space
    {
    thread_local int s;
    } //etc.

i tried to compile my code using 'g++ -std=c++0x -pthread [sourcefile]'. I get the following error:

example.C:6:8: error: thread-local storage is unsupported for the current target
static thread_local int s;
       ^
1 error generated.

If i try to compile the same code on Linux with GCC 4.8.1 whit the same flags, i get a functioning executable file. I'm using clang-503.0.40 (the one which comes with Xcode 5.1.1) on a MacBook Pro running OSX 10.9.3. Can anybody explain me what i'm doing wrong? Thank you!!


回答1:


Try clang++ -stdlib=libc++ -std=c++11. OS X's outdated libstdc++ doesn't support TLS.

Edit

Ok, this works for the normal clang version but not for the Xcode one.

I did a diff against Apple's clang (503.0.38) and the normal released one and found the following difference:

        .Case("cxx_thread_local",
-                 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported() &&
-                 !PP.getTargetInfo().getTriple().isOSDarwin())
+                 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())

So I think this is a bug in Apple's clang version (or they kept it in there on purpose - but still weird, because -v says based on 3.4).




回答2:


Alternatively, you can use compiler extensions such as __thread (GCC/Clang) or __declspec(thread) (Visual Studio).

Wrap it in a macro and you can easily port your code across different compilers and language versions:

#if HAS_CXX11_THREAD_LOCAL
    #define ATTRIBUTE_TLS thread_local
#elif defined (__GNUC__)
    #define ATTRIBUTE_TLS __thread
#elif defined (_MSC_VER)
    #define ATTRIBUTE_TLS __declspec(thread)
#else // !C++11 && !__GNUC__ && !_MSC_VER
    #error "Define a thread local storage qualifier for your compiler/platform!"
#endif

...

ATTRIBUTE_TLS static unsigned int tls_int;



回答3:


The clang compiler included in the Xcode 8 Beta and GM releases supports the C++11 thread_local keyword with both -std=c++11 and -std=c++14 (as well as the GCC variants).

Earlier versions of Xcode apparently supported C-style thread local storage using the keywords __thread or _Thread_local, according to the WWDC 2016 video "What's New in LLVM" (see the discussion beginning at 5:50).




回答4:


Seems like you might need to set the minimum OS X version you target to 10.7 or higher.



来源:https://stackoverflow.com/questions/23791060/c-thread-local-storage-clang-503-0-40-mac-osx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!