[英]LD_PRELOAD and thread local variable
我有一个共享库(libtest.cpp)和一个简单的程序(test.cpp)。 我希望他们共享一个线程局部变量gVar 。 共享库通过LD_PRELOAD链接。
这是我的共享库libtest.cpp的代码:
#include<stdio.h>
__thread int gVar;
void print_gVar(){
printf("%d\n", gVar);
}
下面是test.cpp的代码。
#include<stdio.h>
__thread int gVar;
void __attribute__((weak)) print_gVar();
int main(){
gVar = 10;
print_gVar();
return 0;
}
我使用以下脚本来编译和运行它们。
g++ -g -shared -fPIC -olibtest.so libtest.cpp
g++ -g -fPIC -o test test.cpp
LD_PRELOAD=./libtest.so ./test
预期的结果是10,因为test.cpp中的赋值将影响libtest.cpp中的gVar。 但是,我只得到0.似乎libtest.cpp中的gVar和test.cpp中的gVar没有链接。
我做了一些额外的测试:
如果我将__attribute__((weak))
到任何文件中的gVar
声明中,则输出仍为0。
如果我从两个文件中删除__thread
,则结果为10(成功)。
如果我将gVar
中的extern
和__attribute__((weak))
添加到gVar
的声明中,则会出现分段错误。
我想LD_PRELOAD
和__thread
一定有问题。 但我无法弄清楚。
谁能告诉我如何让它发挥作用? 非常感谢你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.