Home >Backend Development >C++ >How Do I Create and Use Dynamic Shared Libraries (DSLs) in C on Linux?

How Do I Create and Use Dynamic Shared Libraries (DSLs) in C on Linux?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-04 00:25:12939browse

How Do I Create and Use Dynamic Shared Libraries (DSLs) in C   on Linux?

Creating and Utilizing Dynamic Shared Libraries in C on Linux

Dynamic shared libraries (DSLs) offer a powerful mechanism for code reuse and modularity in C . They allow multiple programs to share a single copy of the library code, reducing memory usage and improving performance.

Creating a Dynamic Shared Library

To create a DSL, you'll need to define the classes and functions in a header file and implementation file, respectively. In the header file, declare your class with virtual functions to prevent static linkage. In the implementation file, define the functions and provide wrapper functions for creating and destroying objects.

// myclass.h
class MyClass {
public:
  virtual void DoSomething();

private:
  int x;
};

// myclass.cc
extern "C" MyClass* create_object() { return new MyClass; }
extern "C" void destroy_object(MyClass* object) { delete object; }

Compiling and Linking

On Linux:

g++ -fPIC -shared myclass.cc -o myclass.so

On Mac OS X:

g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so

Using the Shared Library

In a separate executable, load the DSL using dlopen() and retrieve pointers to the create_object() and destroy_object() functions. Create a class instance using create_object(), use the class methods, and finally call destroy_object() to deallocate the memory.

// class_user.cc
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 = (MyClass*)create();
  myClass->DoSomething();
  destroy(myClass);
}

Compiling and Linking:

On Linux:

g++ class_user.cc -ldl -o class_user

On Mac OS X:

g++ class_user.cc -o class_user

Example Code

The provided example showcases how to create a shared class library, load it in a separate executable, and utilize the class functionality. The main concept involves defining classes and functions, creating wrapper functions for object creation and destruction, loading the library, and calling class methods.

The above is the detailed content of How Do 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn