0

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

File : a.c

    #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'
Pradeep Mahato
  • 41
  • 2
  • 11
  • Unrelated to your problem: Don't compile c-code with a c++ compiler. `mainFile.cpp` should be called `mainFile.c` to make sure that the right compiler is called. – HAL9000 Jan 24 '20 at 01:10
  • @HAL9000 Thank you. Yes, you are correct. I should have compiled using gcc. – Pradeep Mahato Jan 24 '20 at 05:14

1 Answers1

5

The second line — the one which links the executable — needs the -ldl, not the first:

g++ -w mainFile.cpp -ldl -o mainFile
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • 1
    Thank you PSkocik, Jonathan Leffler. I should have read http://man7.org/linux/man-pages/man3/dlopen.3.html properly first. Now I encounter another problem. mainFile_works.cpp: In function ‘int main(int, char**)’: mainFile_works.cpp:23:22: error: invalid conversion from ‘void*’ to ‘void (*)()’ [-fpermissive] void (*f)() = dlsym(lib, "abc"); When I compile it using the flag -fpermissive, I get the following error dlsym for f1 failed: ./a.so: undefined symbol: abc Please help. – Pradeep Mahato Jan 24 '20 at 05:07