0

I am trying to use the __thread specifier to create a thread local variable. This works OK in the following code:

#include <stdio.h>
#include <pthread.h>

static __thread int val;

int main()
{
  val = 10;
}

But if I try to use the __thread specifier in a class as follows:

#include <stdio.h>
#include <pthread.h>

class A
{
public:
  A();
  static __thread int val;
};

A::A()
{
  val = 10;
}

int main()
{
  A a;
}

I get the compiler error: undefined reference to 'A::val'

Really Studly
  • 21
  • 1
  • 5
  • That is **not** a compiler error. It's a linker error. – Kerrek SB Sep 07 '12 at 15:16
  • possible duplicate of [C++: undefined reference to static class member](http://stackoverflow.com/questions/272900/c-undefined-reference-to-static-class-member) – jogojapan Oct 30 '12 at 13:04

3 Answers3

3

You've only declared the static variable; you must also define it outside the class (in just one source file, if you have multiple source files):

int __thread A::val;
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • @KerrekSB: Which I'm also not familiar with :). But now I've managed to fire up the compiler, and confirm that you do need it in the definition. – Mike Seymour Sep 07 '12 at 15:20
  • 1
    @KerrekSB: Unfortunately, it is not, since __thread does not know about ctors and dtors. – PlasmaHH Sep 07 '12 at 15:26
  • @PlasmaHH: Are you sure, even in `g++` with `-std=c++11`? Interesting. But I think it plays the same grammatical role. – Kerrek SB Sep 07 '12 at 15:27
  • @KerrekSB: Yes I am (at least for gcc 4.7, don't know if there are any plans to change it). Note that in C++11 thread_local is a storage class specifier on its own, while the gcc extension is just a "special static". So "__thread static" is similar to "thread_local". – PlasmaHH Sep 10 '12 at 09:40
0

Static variables have to defined outside the class declaration scope. Like this:

int A::val;
  • *non-integral* static variables have to be *initialized* outside the class declaration, but any type can be declared within the class. – ssube Sep 07 '12 at 19:28
0

You should define it like:

/\*static\*/ __thread int A::val;

The __thread keyword must be ahead of int.

dbajtr
  • 2,024
  • 2
  • 14
  • 22