rd4*_*8qx 8 gcc constructor shared-libraries ld
我有以下问题.我写了一个共享库
#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;
}
Run Code Online (Sandbox Code Playgroud)
并使用编译它
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));
}
Run Code Online (Sandbox Code Playgroud)
我编译并开始使用
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
程序的输出由下式给出
testprog初始化2.0000000000e + 01清理
如果库是动态链接的,为什么不执行构造函数?
我使用以下版本
GNU ld(GNU Binutils; openSUSE 11.3)2.20.0.20100122-6 gcc version 4.5.0 20100604 [gcc-4_5-branch revision 160292](SUSE Linux)
预先感谢您的帮助!
编辑:2011-04-13,11:05
非常感谢luxifer,
该文件间接帮助!神奇的提示是,应该通过编译器让链接器参与进来......
gcc -fPIC testlib.c -shared -Wl,-soname,libtest.so -o libtest.so
作品!!!