char* dlerror()
1.0、参考
1.1、此函数的作用

获得dlopendlsymdlclose的出错信息

1.2、返回值说明

如果dlopendlsymdlclose这些函数错误,此函数的返回值为非NULL

如果dlopendlsymdlclose这些函数没有错误,此函数的返回值为NULL

1.4、使用示例

step1、编写一个C源程序add.c,其内容如下

int add(int a, int b) {
    return a + b;
}

step2、使用gcc命令将add.c编译为动态库

gcc -shared -fPIC -o libadd.so add.c

step3、编写一个C源程序main.c,其内容如下

#include <stdio.h>
#include <dlfcn.h>

int main(int argc, char* argv[]) {
    if (1 == argc) {
        perror("please provide a library path");
        return 1;
    }

    void* handle = dlopen(argc[1], RTLD_LAZY);
    if (NULL == handle) {
        printf("load %s error, %s\n", argc[1], dlerror());
        return 1;
    }
    printf("load %s success.\n", argc[1]);

    int (*add)(int a, int b);
    add = dlsym(handle, "add");
    int value = add(2, 3);
    printf("add(2, 3) = %d\n", value);

    int statusCode = dlclose(handle);
    printf("unload %s %s!\n", argc[1], statusCode ? "failed" : "success");
    return statusCode;
}

step4、使用gcc命令将mian.c编译为可执行文件

gcc -o main main.c

step5、运行main可执行文件

./main libadd.so

运行结果如下:

load libadd.so success.
add(2, 3) = 5
unload libadd.so success.

注意:这种加载动态库的方式,不需要我们在编译的时候进行链接用到的动态库。 相比于动态链接,这种动态加载更灵活。

source code on GitHub