我是为 Linux 平台开发共享库的新手。
是否有我可以在 .SO 中定义的函数,该函数将在加载库时被调用dlopen()
?
如果你使用 GCC 或兼容的编译器,你可以声明一个函数,__attribute__((constructor))
它会在加载时被调用。就像是
__attribute__((constructor))
void init()
{
puts("Hello dynamic linkage world!");
}
不,系统定义的共享对象中没有标准的“入口点”。使用的给定应用程序dlopen()
可能会定义一个标准符号名称,用作以这种方式加载的模块的入口点。然后,主机应用程序将使用dlsym()
按名称查找该符号以调用它。
但是大多数应用程序根本不直接使用 dlopen ——而且您还没有解释为什么您认为应该这样做。
来自手册页: 过时的符号 _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.**