我正在尝试使用__thread说明符来创建线程局部变量。这可以在以下代码中正常工作:
#include <stdio.h>
#include <pthread.h>
static __thread int val;
int main()
{
val = 10;
}
但是如果我尝试在类中使用__thread说明符,如下所示:
#include <stdio.h>
#include <pthread.h>
class A
{
public:
A();
static __thread int val;
};
A::A()
{
val = 10;
}
int main()
{
A a;
}
我收到编译器错误:未定义引用'A :: val'
答案 0 :(得分:3)
你只声明了静态变量;你还必须在类之外定义它(如果你有多个源文件,只在一个源文件中):
int __thread A::val;
答案 1 :(得分:0)
静态变量必须在类声明范围之外定义。像这样:
int A::val;
答案 2 :(得分:0)
您应该将其定义为:
/\*static\*/ __thread int A::val;
__thread
关键字必须位于int
之前。