Skip to content
Advertisement

dlopen Segmentation fault error when get a instance from shared library’s exported function

I have been stuck in a problem for several days when using dlopen/dlsym to deal with the shared object. I desperately need your help!

There are three headers/source files: Animal.h, Animal.cpp and test.cpp, and two products: libanimal.so and a.out.

Here is the source code:

Animal.h:

JavaScript

Animal.cpp

JavaScript

and the last one test.cpp which contained the main entry of the application:

JavaScript

First, I built libanimal.so shared library by the following command:

JavaScript

Then I built the executable, a.out:

JavaScript

Both the above commands ran well without any error, but when I execute a.out, errors came out:

JavaScript

I have searched lots of blogs/documentations, but all of them just post a really simple example:
The function they export always return like a std::string or char or int which is built-in type, not something like a object of a user-defined class, just like the showcase above (the createAnimal function).

So what’s wrong with this? Could you please help me figuring out ?
Thank you !

BTW, my environment is:

JavaScript

Advertisement

Answer

Ok, my suspicion from the comment has confirmed itself. The problem is with the early binding on animal->shout() which resolves at compile time to a call to _ZN6Animal5shoutB5cxx11Ev and this symbol is nowhere to be found.

If I change it to virtual (late binding, resolved at runtime through a vtable):

JavaScript

Now it runs.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement