dlopen fails to undefined symbol for function that is a prototype

1.3k views Asked by At

I am writing a shared library on Linux (64-bit) with C11.

I created 3 C and H files.

dll.c

#include "dllman.h"

void start(){
    pipeListeningThreadFunc( NULL );
}

dllman.h

#include <stdio.h>

void* pipeListeningThreadFunc( void* args );

dllman.c

#include "dllman.h"

void* pipeListeningThreadFunc( void* args ){
    printf("Blah");
    return NULL;
}

Compiling code as follows

gcc -std=gnu11 -c -Wall -Werror -fpic -lpthread dll.c
gcc -std=gnu11 -shared -fpic -o dll.so dll.o

Everything is okay until this point. dll.so file is created. But when I use dlopen function to load the library with as:

test.d

...
void* lh = dlopen("./dll.so", RTLD_NOW | RTLD_GLOBAL);
...

dlerror gives me: dlopen error: ./dll.so: undefined symbol: pipeListeningThreadFunc

I don't understand what is wrong with this.

To be able to understand the problem, I moved the implementation of function pipeListeningThreadFunc to dllman.h, and compiled in same way. This time everything works properly.

What is wrong with defining function as prototype? Why can't it find the function when it is defined as prototype in header file and implemented in C file?

1

There are 1 answers

6
Alex F On BEST ANSWER

I think you meed to execute the following commands:

gcc -std=gnu11 -c -Wall -Werror -fpic -lpthread dll.c
gcc -std=gnu11 -c -Wall -Werror -fpic -lpthread dllman.c
gcc -std=gnu11 -shared -fpic -o dll.so dll.o dllman.o

Your commands are missing dllman.c

Linux allows to build libraries that are missing some symbols (in your case, dll.so doesn't contain pipeListeningThreadFunc function). However, when library is loaded, pipeListeningThreadFunc must be found anywhere - whether in this library or another library. Since this function doesn't exist, dlopen fails.