gpt4 book ai didi

gcc - 不执行共享库构造函数

转载 作者:行者123 更新时间:2023-12-04 08:53:28 26 4
gpt4 key购买 nike

我有以下问题。我写了一个共享库

#include <stdio.h>
#include <stdlib.h>

static void __attribute__ ((constructor)) test_init(void);
static void __attribute__ ((destructor)) test_clean(void);

/* Initialization */
static void test_init(void){
fprintf(stderr,"initialized\n");
fflush(stderr);
}
/* CleanUp */
static void test_clean(void){
fprintf(stderr,"cleaned up\n");
fflush(stderr);
}

double test (double x){
return 2.0*x;
}

并使用编译它

gcc -c -fPIC teSTLib.c -o teSTLib.o

ld -shared -o libtest.so teSTLib.o

然后我将它包含在一个测试程序中
#include <stdio.h>
#include <stdlib.h>
extern double test(double x);
void main(void){

printf("%.10e\n",test(10.0));
}

我编译并开始使用

gcc testprog.c -o testprog -L。 -ltest

LD_LIBRARY_PATH=。 ./测试程序

然后输出由下式给出

2.0000000000e+01

这意味着不执行构造函数/析构函数。另一方面,如果我编译

ar rvs teSTLib.a teSTLib.o

gcc testprog.c teSTLib.a -o testprog

程序的输出由下式给出

测试程序
初始化
2.0000000000e+01
清理

如果库是动态链接的,为什么不执行构造函数?

我使用以下版本

GNU ld(GNU Binutils;openSUSE 11.3)2.20.0.20100122-6
gcc 版本 4.5.0 20100604 [gcc-4_5-branch 修订版 160292] (SUSE Linux)

预先感谢您的帮助!

编辑:2011-04-13, 11:05

非常感谢luxifer,

该文件间接帮助了!神奇的提示是,应该通过编译器让链接器参与进来……

gcc -fPIC testlib.c -shared -Wl,-soname,libtest.so -o libtest.so



作品!!!

最佳答案

Gcc 的构造函数处理与 ELF 构造函数处理不同,相反,它位于它之上。要工作,您需要链接 gcc 启动文件中提供的胶水代码。

最简单的方法是使用 gcc 链接:

gcc -shared -o testlib.so testlib.o

关于gcc - 不执行共享库构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5646211/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com