小编典典

Linux上的C ++动态共享库

linux

这是使用g
++
进行动态共享库编译的后续版本。

我正在尝试在Linux上的C++中创建一个共享的类库。当我尝试使用库中定义的类时,我的问题开始了。我链接到的第二篇教程展示了如何加载用于创建库中定义的类的对象的符号,但是没有_使用_ 这些对象来完成任何工作。

有谁知道用于创建共享C ++类库的更完整的教程,该教程还显示了如何在单独的可执行文件中 使用
这些类?一个非常简单的教程,显示了对象的创建,使用(简单的getter和setter方法就可以了)和删除将是很棒的。链接或引用某些开源代码来说明共享类库的使用也同样不错。


尽管来自codelogic和nimrodm的答案确实有用,但我只是想补充一点,因为提出了这个问题,所以我选择了《Beginning
LinuxProgramming》
的副本,并且其第一章包含示例C代码以及有关创建和使用静态库和共享库的良好解释。
。这些示例可通过该书的旧版
Google图书搜索获得。


阅读 243

收藏
2020-06-02

共1个答案

小编典典

myclass.h

#ifndef __MYCLASS_H__
#define __MYCLASS_H__

class MyClass
{
public:
  MyClass();

  /* use virtual otherwise linker will try to perform static linkage */
  virtual void DoSomething();

private:
  int x;
};

#endif

myclass.cc

#include "myclass.h"
#include <iostream>

using namespace std;

extern "C" MyClass* create_object()
{
  return new MyClass;
}

extern "C" void destroy_object( MyClass* object )
{
  delete object;
}

MyClass::MyClass()
{
  x = 20;
}

void MyClass::DoSomething()
{
  cout<<x<<endl;
}

class_user.cc

#include <dlfcn.h>
#include <iostream>
#include "myclass.h"

using namespace std;

int main(int argc, char **argv)
{
  /* on Linux, use "./myclass.so" */
  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 );
}

在Mac OS X上,使用以下命令进行编译:

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

在Linux上,使用以下命令进行编译:

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

如果这是针对插件系统的,则可以将MyClass用作基类,并定义所有所需的虚拟函数。然后,插件作者将从MyClass派生,重写虚拟函数并实现create_objectdestroy_object。您的主应用程序无需进行任何更改。

2020-06-02