要在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")))
#endif
class 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;
}
編譯和鏈接這個程序時,需要將動態庫鏈接到該程序中。