2

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?

Marco Strigl
  • 43
  • 1
  • 4

1 Answers1

4

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • And I get criticized for always doing things like `if ( NULL == lib ) ...`. If you put the constant first any mistake in the comparison operator will cause a compilation error. And `-Wall` is great, too. If the people who wrote the compiler you're using to turn your source code into a runnable binary took the extra effort to warn you that they think something in your code is sketchy, it's a good idea to believe them. Even to the point of treating any warning as an actual error. – Andrew Henle Mar 09 '16 at 16:37
  • @AndrewHenle There's an argument to be made regarding using a coding style that exposes certain types of bugs versus coding in a style that's more readable but using the proper compiler flags to catch bugs. It can go either way. – dbush Mar 09 '16 at 16:40
  • Thank you so much. I am so blind. I was so focused that the problem must be in the dynamic linking logic that i was not aware of that typo. Normally i always compile with -Wall. I do not know why i missed it this time. – Marco Strigl Mar 09 '16 at 17:16