问题描述
我最近学习了 LD_PRELOAD 技巧 (What is the LD_PRELOAD trick?),可用于调试或修补程序。
我想看看我是否可以结合这个技巧和 GCC 析构函数 (https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html) 来调试一个变量,并创建了一个非常简单的案例来磨练我的理解。
我有 test.c
如下:
#include <stdio.h>
int a = 1;
void __attribute__((destructor)) run_last() {
printf("Destructor: %d\n",a);
}
和 test_2.c
如下:
#include <stdio.h>
#include "test.c"
int main()
{
extern int a;
printf("main: %d\n",a++);
}
我使用命令test.c
编译gcc -Wall -O3 -fPIC -shared test.c -o test.so
以生成共享对象,并使用命令test_2.c
编译gcc test_2.c -o test_2
现在,我希望看到的是输出:
main: 1
Destructor: 2
产生这种期望的原因是因为我在打印语句后对变量 a
进行了后递增,并且当我使用 extern int a
时,据我所知,我正在递增变量在 a
中声明的 test_2.c
,其中包含析构函数 run_last()
,它将使用 a
的最新值。
然而,相反,我得到了这样的输出:
为什么这里有一个 Destructor: 1
?根据我的理解,析构函数不应该只被调用一次吗?我目前的猜测是,当我在 #include "test.c"
中 test_2.c
时,有一种我目前不理解的行为。
感谢您的任何建议或指导,
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)