2013-05-29 35 views

回答

2

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

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

+0

他们为什么不直接使用dlopen? – opc0de

+0

正常应用程序不直接使用它,因为它们在构建时显式链接到它们所需的共享库。也就是说,指令被烘焙到每个可执行文件中,告诉加载器加载哪些库,而不需要应用程序中的任何显式代码。您可以通过在可执行文件上运行程序'ldd'来以这种方式自动加载哪些库。明确使用'dlopen()'是为实现“插件”体系结构的程序 - 例如程序在运行时不知道它们需要哪些库。例如:Firefox,Python,Photoshop .... –

2

如果您使用的是GCC或兼容的编译器,您可以声明一个函数__attribute__((constructor)),它将在加载时被调用。喜欢的东西

__attribute__((constructor)) 
void init() 
{ 
    puts("Hello dynamic linkage world!"); 
} 
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.**