【发布时间】:2011-08-04 12:14:44
【问题描述】:
我有以下问题。我写了一个共享库
#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=。 ./testprog
那么输出由下式给出
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
有效!!!
【问题讨论】:
-
main() 的返回类型是 int。总是。
标签: gcc constructor shared-libraries ld