在库加载时执行的函数

时间:2013-05-29 12:24:44

标签: linux shared-libraries

我是开发Linux平台的共享库的新手。

我是否可以在.SO中定义一个函数,该函数将在dlopen()加载库时调用?

3 个答案:

答案 0 :(得分:2)

不,没有标准的"切入点"在系统定义的共享对象中。使用dlopen()的给定应用程序可能会定义一个标准符号名称,以用作以这种方式加载的模块的入口点。然后,主机应用程序将使用dlsym()按名称查找该符号,以便调用它。

但是大多数应用程序根本不直接使用dlopen - 而且你还没有解释为什么你认为应该这样做。

答案 1 :(得分:2)

如果您使用的是GCC或兼容的编译器,则可以使用__attribute__((constructor))声明一个函数,并在加载时调用它。像

这样的东西
__attribute__((constructor))
void init()
{
    puts("Hello dynamic linkage world!");
}

答案 2 :(得分:1)

来自手册页: 过时的符号_init()和_fini()  链接器识别特殊符号_init和_fini。如果动态        库导出一个名为_init()的例程,然后执行该代码        在加载之后,在dlopen()返回之前。如果是动态库        导出一个名为_fini()的例程,然后调用该例程        在卸载库之前。如果您需要避免链接        对于系统启动文件,这可以通过使用        gcc(1)-nostartfiles命令行选项。

   Using these routines, or the gcc -nostartfiles or -nostdlib options,
   is not recommended.  Their use may result in undesired behavior,
   since the constructor/destructor routines will not be executed
   (unless special measures are taken).

   **Instead, libraries should export routines using the
   __attribute__((constructor)) and __attribute__((destructor)) function
   attributes.  See the gcc info pages for information on these.
   Constructor routines are executed before dlopen() returns, and
   destructor routines are executed before dlclose() returns.**
相关问题