Operating System - HP-UX
1833873 Members
2953 Online
110063 Solutions
New Discussion

C++ dynamic shared lib loading

 
David Storrie
Occasional Contributor

C++ dynamic shared lib loading

I'm trying to implement dynamic loading of a shared library instead of implicit loading. However, I'm having problems with symbol resolution. Specifically I'm stuck on the constructor and destructor - how to declare myClass* myVar = new myClass() when myClass() is bound late?
1 REPLY 1
Mike Stroyan
Honored Contributor

Re: C++ dynamic shared lib loading

This depends on what you are trying to accomplish with dynamic loading. Perhaps you know exactly what the library
will contain but want to do some runtime decision about which of several libraries you want to load in.
It is possible to just make function calls such as constructors even though you don't link with the library. The linker will complain about the unsatisfied references, but it will create a program file anyway. If you compile with 32-bit mode, you need to do a chmod +x a.out after linking because the linker won't make the a.out executable if it is missing symbols. If you compile with 64-bit mode you can link with -Wl,+allowunsat and the linker will warn about unsats but still make an executable a.out. You can run the executable successfully as long as you link with the default "-B deferred" mode and load the library before you make any calls to its function. (You can't have
a direct dependency on a data item because those have to found at program startup.)
You can use a more subtle approach by linking with a shared library that resolves the symbols at link time, but then replace that shared library with a stub at runtime. The stub doesn't have to resolve the same functions that its namesake had at link time. The dld.sl will look for those symbols in any shared library, including ones that you dynamically load later.
The more conventional approach to this is to use only "extern C" functions in a shared library and then use shl_findsym to look up the address of each function that you will call. That would mean that your a.out could not have direct reference to any classes implemented inside the dynamically loaded shared library. You would need to hide class objects behind something like "void *" parameters that you pass in and out of the access functions.