【问题标题】:Shared Library Constructor is not executed未执行共享库构造函数
【发布时间】: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


【解决方案1】:

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

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

gcc -shared -o testlib.so testlib.o

【讨论】:

    【解决方案2】:

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

    我不是该领域的专家,但通过 Google 快速搜索得到了this。只阅读文档的开头,如果我做对了,问题是这样的:

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

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

    所以如果我做对了,动态链接器只加载库的一部分,即需要的函数,而不是整个库,那么这就解释了为什么当你的库被动态链接时没有调用你的构造函数。

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 2021-04-13
      相关资源
      最近更新 更多