要在C++动态库中导出类,可以使用以下步骤:
- 定义一个类并实现其成员函数。
- 在类的声明前加上
__declspec(dllexport)标记(Windows平台)或__attribute__((visibility("default")))标记(Linux平台),以将该类及其成员函数导出。 - 将类的定义和实现放在头文件中,并编译为动态链接库。
以下是一个简单示例:
example.h:
#ifndef EXAMPLE_H#define EXAMPLE_H#ifdef _WIN32 // Windows平台下的导出声明#ifdef EXAMPLE_DLL_EXPORTS#define EXAMPLE_API __declspec(dllexport)#else#define EXAMPLE_API __declspec(dllimport)#endif#else // Linux平台下的导出声明#define EXAMPLE_API __attribute__((visibility("default")))#endifclass EXAMPLE_API MyExampleClass {public:MyExampleClass();void HelloWorld();};#endif // EXAMPLE_H
example.cpp:
#include "example.h"#include <iostream>MyExampleClass::MyExampleClass() {}void MyExampleClass::HelloWorld() {std::cout << "Hello, World!" << std::endl;}
然后,你可以将这些文件编译为动态链接库。在Windows下,你需要指定 EXAMPLE_DLL_EXPORTS 宏进行导出,例如使用 Visual Studio 编译;在Linux下,你需要使用 -fPIC 参数编译为位置独立码。
最后,可以创建一个演示程序来使用这个动态链接库:
main.cpp:
#include "example.h"int main() {MyExampleClass myObj;myObj.HelloWorld();return 0;}
编译和链接这个程序时,需要将动态库链接到该程序中。