简体   繁体   中英

undefined reference to dlopen

I have one C program which I want to load into my running C program. Following are the snippet

File : ac

    #include <stdio.h>

    void abc() { 
      printf("This is abc\n"); 
    }

File : mainFile.cpp

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

    int main(int argc, char **argv) {

      void *lib = dlopen("./a.so", RTLD_LAZY);
       if (!lib) {
         printf("dlopen failed: %s\n", dlerror());
         return 1;
      }
      void (*f)() = dlsym(lib, "abc");
      if (f) {
          f();
      } else {
          printf("dlsym for f1 failed: %s\n", dlerror());
      }

      dlclose(lib);
      return 0;
    }

I am compiling with the following commands

    gcc -fpic -g -shared -ldl -o a.so a.c
    g++ -w mainFile.cpp -o mainFile

Output:

/tmp/cc9fYZaf.o: In function `main':
mainFile.cpp:(.text+0x1a): undefined reference to `dlopen'
collect2: error: ld returned 1 exit status

I am compiling in Ubuntu 16.04 with gcc version gcc (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609

Please help

Note: I have followed the following references but none helped.

  1. Can you dynamically compile and link/load C code into a C program?
  2. undefined reference to `dlopen' since ubuntu upgrade
  3. undefined reference to `dlopen'

第二行——链接可执行文件的行——需要-ldl ,而不是第一行:

g++ -w mainFile.cpp -ldl -o mainFile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM