Creating and Using Dynamic Shared Libraries in C on Linux
Dynamic shared libraries (DSLs) allow multiple programs to share code, reducing memory usage and improving efficiency. In C , DSLs enable the creation of reusable class libraries accessible to multiple executables.
Creating the DSL
To create a DSL, define the class interface and implementation in header and source files (e.g., myclass.h and myclass.cc). Ensure the class includes a virtual destructor and public methods marked extern "C" to facilitate symbol loading.
Using the DSL
To utilize a DSL in a separate executable, perform the following steps:
Example Code
myclass.h
#include <iostream> class MyClass { public: MyClass(); virtual void DoSomething(); private: int x; };
myclass.cc
#include "myclass.h" extern "C" MyClass* create_object() { return new MyClass; } extern "C" void destroy_object(MyClass* object) { delete object; } MyClass::MyClass() { x = 20; } void MyClass::DoSomething() { std::cout << x << std::endl; }
class_user.cc
#include <dlfcn.h> #include <iostream> #include "myclass.h" int main() { void* handle = dlopen("./myclass.so", RTLD_LAZY); MyClass* (*create)(); void (*destroy)(MyClass*); create = (MyClass* (*)())dlsym(handle, "create_object"); destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object"); MyClass* myClass = create(); myClass->DoSomething(); destroy(myClass); }
Compilation and Execution
On Mac OS X:
On Linux:
Execute class_user to use the MyClass shared library. It will instantiate and utilize the MyClass object successfully.
The above is the detailed content of How Can I Create and Use Dynamic Shared Libraries (DSLs) in C on Linux?. For more information, please follow other related articles on the PHP Chinese website!