C++导出函数 或数据
时间: 2024-05-06 15:17:04 浏览: 8
C++中导出函数或数据,通常需要使用关键字 `extern` 和 `__declspec(dllexport)`。
对于函数,需要在函数声明前加上 `extern "C" __declspec(dllexport)`,例如:
```cpp
extern "C" __declspec(dllexport) int add(int a, int b);
```
对于数据,需要在数据声明前加上 `extern "C" __declspec(dllexport)`,例如:
```cpp
extern "C" __declspec(dllexport) int global_var;
```
在编译时,需要将这些导出函数或数据所在的源文件编译成动态链接库(DLL)或静态链接库(LIB)。在编译时,需要加上对应的选项,例如:
```bash
# 编译动态链接库
g++ -shared -o mydll.dll mylib.cpp
# 编译静态链接库
g++ -c mylib.cpp
ar rcs libmylib.a mylib.o
```
最后,在使用这些导出函数或数据的程序中,需要使用 `LoadLibrary` 和 `GetProcAddress` 函数来动态加载并调用这些函数或数据,例如:
```cpp
// 动态加载 DLL
HMODULE hModule = LoadLibrary("mydll.dll");
if (hModule != NULL) {
// 获取函数指针
typedef int (*AddFunc)(int, int);
AddFunc add = (AddFunc)GetProcAddress(hModule, "add");
if (add != NULL) {
int result = add(1, 2);
// 使用结果
}
}
// 加载静态链接库
#include "mylib.h"
int result = add(1, 2);
// 使用结果
```