通过下面的链接,我了解了如何创建和使用共享库。https://www.cprogramming.com/tutorial/shared-libraries-linux-gcc.html
Step 1: Compiling with Position Independent Code
$ gcc -c -Wall -Werror -fpic foo.c
Step 2: Creating a shared library from an object file
$ gcc -shared -o libfoo.so foo.o
Step 3: Linking with a shared library
$ gcc -L/home/username/foo -Wall -o test main.c -lfoo
Step 4: Making the library available at runtime
$ export LD_LIBRARY_PATH=/home/username/foo:$LD_LIBRARY_PATH
$ ./test
This is a shared library test...
Hello, I am a shared library然而,我有几个问题:
在给定的链接中,不使用dlopen(),这是打开共享库所必需的。这段代码在没有dlopen()调用的情况下是如何工作的?
提前谢谢。
发布于 2020-08-08 08:53:15
动态库
当我们将应用程序链接到共享库时,链接器会在应用程序加载时留下一些存根(未解决的符号)来填充。这些存根需要在运行时或应用程序加载时由一个名为动态链接器的工具填充。
共享库的加载有两种类型,
在这里,程序与共享库链接,内核在执行时加载库(如果它不在内存中)。在上述链接中对此进行了解释。
对于创建“插件”架构非常有用。顾名思义,动态加载是指按需加载库,并在执行过程中进行链接。程序通过使用库调用函数来获得完全的控制。这是使用dlopen()、dlsym()、dlclose()完成的。函数打开一个库并准备使用它。有了这个系统调用,就可以打开一个共享库并使用它的函数,而不必与它链接。您的程序刚刚开始,当它发现需要使用特定库中的函数时,就调用dlopen()来打开这个库。如果库在系统上不可用,则函数返回NULL,由程序员来处理。你可以让程序优雅地死去。
DL示例:此示例加载数学库并打印2.0的余弦,并在每一步(推荐)检查错误:
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen ("/lib/libm.so.6", RTLD_LAZY);
if (!handle) {
fputs (dlerror(), stderr);
exit(1);
}
cosine = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
printf ("%f\n", (*cosine)(2.0));
dlclose(handle);
}在编译DL源代码时使用-rdynamic。
例如。gcc -rdynamic -o方案1.c -ldl
https://stackoverflow.com/questions/63306734
复制相似问题