LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   What is the correct way to write a working shared library in C++? (https://www.linuxquestions.org/questions/programming-9/what-is-the-correct-way-to-write-a-working-shared-library-in-c-606508/)

golden97 12-13-2007 06:58 AM

What is the correct way to write a working shared library in C++?
 
Hi, I am wondering how to write a shared library in C++.
I already know a little bit about the dlopen() API.
How do you get shared libraries to work with programs written in C++?

osor 12-14-2007 04:01 PM

Well, there are two ways to use shared libraries (regardless of whether you’re dealing with C or C++): dynamic linking and dynamic loading. The easiest of the two (both conceptually and in terms of practical use in C++) is dynamic linking.

When you create a shared object for dynamic linking, it is much like creating a static object archive for static linking (a static archive is just an amalgam of object files into a single object file). When you use it, from a program, you place it in the library search path and pass the soname to the linker (e.g., “-lfoo” would dynamically link to the shared object libfoo.so or the static object archive libfoo.a). You can use the same classes and functions as if they were in a different object, the only thing is that they will not be resolved until you begin to run the program. As long as any name mangling is the same in both the library and the program using it, nothing bad should happen. Notice that the actual linking occurs at compile time, but symbol resolution occurs at runtime.

Dynamic loading is more difficult (at least in C++). This sort of shared object use occurs for example if you are using functions from a “plugin” or something. Instead of linking at compile time, you actually instruct your program to load a shared object during runtime (this is not done by ld.so at initialization, but by your program itself during any point in its execution). The API used here is usually dlopen(). The problem is that you give dlopen() a symbol’s name to resolve. The symbol’s name has most likely been mangled from the original name, and it is not usually useful to try to guess the mangling (which happens to be implementation-specific, and may even vary between different versions of implementations). The easiest way to overcome this is to explicitly disable name mangling when creating the shared object (i.e., by using “extern "C"”). The problem here is that you lose things like the ability to overload. The other problem is with classes (which are not covered by dlopen()). In the case of classes, you most likely need to create separate “helper” or “factory” functions whose sole purpose is to instantiate and return a class, and then delete/clean up the class when it’s finished.


All times are GMT -5. The time now is 05:00 PM.