Linux C++动态库

C++类头文件[tdl.h]

#ifndef __TEST_DL_H__
#define __TEST_DL_H__
 
#include "ctdl.h"
 
class TestDL:public CTestDL
{
public:
    TestDL(){};
    virtual ~TestDL(){};
    virtual void test(const char *pstr);
    virtual void hello();
};
 
#endif

C++类源文件[tdl.cpp]

#include <stdio.h>
#include <unistd.h>
 
#include "tdl.h"
 
CTestDL *GetClass_DL(void)
{
    return (new TestDL());
}
 
void TestDL::hello()
{
    printf("hello,this is library message\n");
}
 
void TestDL::test(const char *pstr)
{
    printf("USE library say:%s\n",pstr);
}

 C++类库外部引用文件[ctdl.h]

#ifndef __CTEST_DL_H__
#define __CTEST_DL_H__
 
 
class CTestDL
{
public:
  virtual void test(const char *pstr) = 0;
  virtual void hello() = 0;
};
 
extern "C" CTestDL *GetClass_DL(void);
 
 
#endif

 编译生成.so动态库:

  g++ -shared -lc -s -o libtdlc.so tdl.cpp

   使用的时候,只需要libtdlc.so库文件和ctdl.h头文件

C++调用库源文件[test.cpp]

#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>
 
#include "ctdl.h"
 
int main(int argc,char **argv)
{
    CTestDL *(*pTestDLObj)(void);
    dlerror();
 
    void *lib_dl = dlopen("./libtdlc.so",RTLD_LAZY);
    if(NULL == lib_dl)
    {
        printf("load library libtdlc.so error.\nErrmsg:%s\n",dlerror());
        return -1;
    }
    pTestDLObj = (CTestDL *(*)(void))dlsym(lib_dl,"GetClass_DL");
    const char *dlmsg = dlerror();
    if(NULL != dlmsg)
    {
        printf("get class testdl error\nErrmsg:%s\n",dlmsg);
        dlclose(lib_dl);
        return -1;
    }
 
    CTestDL *pTestdl = (*pTestDLObj)();
    pTestdl->hello();
    pTestdl->test("success");
 
    delete pTestdl;
    dlclose(lib_dl);
    return 0;
}

编译生成应用程序:

  g++ -rdynamic -ldl -s -o test test.cpp

 

刚开始写动态库的时候,TestDL类声明里面没写构造和析构函数,在运行test后提示:__ZIXGnCTestDL undefine,加上之后就正常了。这个不知道是什么原因。在TestDL和CTestDL两个类中都添加构造和析构函数,也会有这个提示。

 

备注:出现__XXXXClass undefine和typeinfo xxxclass / vtable xxxxclass undefine解决方法:

  在定义虚函数时,virtual int test()=0;即可


猜你喜欢

转载自blog.csdn.net/huangyimo/article/details/80565080