共享库构造函数未执行

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

作品!!!

小智 -3

本文仅供参考,但为了方便起见,我会去您的办公室:)

我不是该领域的专家,但快速的谷歌搜索给了我这个。只阅读文档的开头,如果我理解正确,问题是这样的:

静态链接你的程序在执行时是独立的......它包含整个库,并且当你运行它时它完全加载到内存中。

当在执行时从程序调用库函数时动态链接,链接器会尝试通过查看函数是否在某个库中具有实现来解析函数上所有未解析的引用。如果是这样,它会加载此实现,即仅加载函数代码。

因此,如果我得到了正确的结果,并且动态链接器仅加载库的一部分(即所需的函数),而不是整个库,那么这将解释为什么当动态链接库时不调用构造函数。