0

I'm trying thread-local-storage with a C++ class:

struct TestTLS
{
    TestTLS()
    {
        TestTLS::g_tls_val = 1;
    }
    
    int getTls()
    {
        return TestTLS::g_tls_val;
    }
    
    void setTls(int v)
    {
        TestTLS::g_tls_val = v;
    }
    
    
private:
    static __thread int g_tls_val;
    
};

and then:

TestTLS tls;
int ff = tls.getTls();
tls.setTls(3);
int ee = tls.getTls();

But I'm getting the following errors:

Undefined symbols for architecture arm64:
  "TestTLS::g_tls_val", referenced from:
      TestTLS::getTls() in main.o
      TestTLS::setTls(int) in main.o
      TestTLS::TestTLS() in main.o

What am I doing wrong there?

c00000fd
  • 20,994
  • 29
  • 177
  • 400
  • 1
    For one don't use symbols starting with double `__`. They are reservered for compiler/library builders use [thread_local](https://en.cppreference.com/w/cpp/keyword/thread_local) instead. The actual reason for your comiler error is you declared `static __thread int g_tls_val;` but didn't initalize it anywhere. – Pepijn Kramer Dec 29 '22 at 13:40
  • Never ever use things, that start with `__`(2 underscores). Except of few well defined variables(like `__cplusplus`) everything is UB. For thread local variables use `thread_local` – Deumaudit Dec 29 '22 at 13:40
  • This has nothing to do with thread local storage, but with an uninstantiated static class member. You'll get the same error without `__thread`. Try it. Fix this without the `__thread`, then add it back in. – Sam Varshavchik Dec 29 '22 at 13:45
  • Oh, my bad. I guess it has nothing to do with the thread-local-storage. – c00000fd Dec 29 '22 at 14:56

0 Answers0