C dlsym undefined symbol

守給你的承諾、 提交于 2021-02-11 07:02:13

问题


I tried to play around with dynamic linking, but are not able to get a working example. My library code is:

dyn_shl.c:

#include <stdio.h>
#include <dyn_shl.h>
void hello (void)
{
  puts("Hello, Im a loaded shared library");
}

The header file (dyn_shl.h)

extern void hello(void);

I compile them with:

gcc -fPIC -g -c source/dyn_shl.c -o objects/dyn_shl.o -Iincludes/ -DDEBUG -Wall
gcc -shared -W1,-soname,libhello.so -o objects/libhello.so objects/dyn_shl.o

Now a nm -D objects/libhello.so shows:

0000000000201030 B __bss_start
                 w __cxa_finalize
0000000000201030 D _edata
0000000000201040 B _end
0000000000000648 T _fini
                 w __gmon_start__
00000000000005f4 T hello
00000000000004d8 T _init
                 w _Jv_RegisterClasses
                 U puts

There is my hello Symbol at 00000000000005f4.

My main source is in dyn_ratd.c:

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

int main (void)
{
  void* lib;
  void (*print_my)(void);
  char *error;

  lib = dlopen("/root/dev/src/wm_rat/objects/libhello.so",RTLD_NOW);
  if(lib = NULL) {
    return printf("ERROR: Cannot load library");
  }
  print_my = dlsym(lib, "hello");
        if ((error = dlerror()) != NULL)  {
            fputs(error, stderr);
            exit(1);
        }
}

I build it with

gcc -rdynamic -o bin/dyn_ratd source/dyn_ratd.c -ldl

When I am running bin/dyn_ratd i get undefined symbol: hello

I don't see where I'm missing the point. Anyone knowing what i am missing?


回答1:


Here's your problem:

if(lib = NULL) {

Instead of comparing lib to NULL, you're assigning NULL to it. That's why the dlsym call fails.

Change the assignment to a comparison:

if(lib == NULL) {

If you compiled your main source with -Wall it would have warned you of this.



来源:https://stackoverflow.com/questions/35896521/c-dlsym-undefined-symbol

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!