【发布时间】:2015-05-08 02:07:42
【问题描述】:
这里有类似的问题,但他们并没有完全回答我的问题:
- When to use __declspec(dllexport) in C++
- Why do I need __declspec(dllexport) to make some functions accessible from ctypes?
当我使用 MinGW 和 wclang 从 Mac OS X 交叉编译 DLL 时,为什么不使用 __declspec 我的 DLL 可以正常工作?
MinGW DLL sample docs,以及我看到的每一个这样做的参考,都说在函数声明之前使用__declspec(dllexport)。然而,在我的 9,000 行库中没有代码使用它,而且 DLL 运行良好!
例如,这是一个以相同方式构建的人为示例库:
#include <stdio.h>
extern "C" {
int hello(const char* name) {
printf("Hello, %s!\n", name);
return 0;
}
}
在 Mac OS X 10.10.3 上编译:
w32-clang++ test.cpp -shared -o test.dll
生成美观的 DLL:
还有我的 Windows 应用程序:
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
typedef int(*hellofn)(const char*);
int _tmain(int argc, _TCHAR* argv[])
{
DWORD err;
HINSTANCE dll = LoadLibrary(L"E:\\test.dll");
if (!dll) {
err = GetLastError();
std::cout << "Can't load library: " << err << std::endl;
return 1;
}
hellofn hello = (hellofn)GetProcAddress(dll, "hello");
if (!hello) {
err = GetLastError();
std::cout << "Could not load the function: " << err << std::endl;
return 2;
}
int ret = hello("nerd");
std::cout << "hello() returned " << ret << std::endl;
return 0;
}
效果很好:
我是在以某种方式向自己的脚开枪,还是有一些我没有看到的魔法?我在想 wclang (MinGW+clang) 知道以某种方式自动使用 __stdcall 并且不会破坏函数名称?
【问题讨论】: