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

void create_dynamic_library()
{
    FILE *file = fopen("libhello.c", "w");
    fprintf(file, "#include <stdio.h>\n");
    fprintf(file, "void hello() {\n");
    fprintf(file, "    printf(\"Hello from the library!\\n\");}\n");
    fclose(file);
    system("gcc -shared -fPIC -o libhello.so libhello.c");
}

void run_all_files()
{
    system("gcc -o test_dynamic_library test_dynamic_library.c");
    system("./test_dynamic_library");

}

int main()
{
    create_dynamic_library();

    FILE *file = fopen("test_dynamic_library.c", "w");
    fprintf(file, "#include <stdio.h>\n");
    fprintf(file, "#include <dlfcn.h>\n");
    fprintf(file, "int (*module_pr)(void);\n");
    fprintf(file, "int main(void){\n");
    fprintf(file, "     void *h;\n");
    fprintf(file, "    h = dlopen(\"./libmodule.so \", RTLD_NOW|RTLD_GLOBAL);\n");
    fprintf(file, "    module_pr = dlsym(h, \"m_pr\");\n");
    fprintf(file, "    module_pr();\n");
    fprintf(file, "    dlclose(h);\n");
    fprintf(file, "    dlerror();\n");
    fprintf(file, "    return 0;\n");
    fprintf(file, "}\n");
    fclose(file);

    run_all_files();

    return 0;
}
最后修改:2024 年 07 月 07 日
如果觉得我的文章对你有用,请随意赞赏