• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
旧博客
   首页    新随笔    联系   管理    订阅  订阅

'needs to have dll-interface' warning

class 里面有std::vector<std::string> str的时候提示C4251 warning: needs to have dll-interface...

http://www.programmersheaven.com/mb/CandCPP/310449/310449/needs-to-have-dll-interface-warning/

templates can't be exported -- but I think you can safely ignore the error if the application program will not have access to the template object.

似乎STL无法被export到dll解决方法有2个:

1. #pragma warning(disable, 4251)

2.定义之前添加

template class UX_EXPORTS std::allocator<std::string>;
template class UX_EXPORTS std::vector<std::string, std::allocator<std::string>>;

然后定义std::vector<std::string> files;就没有warning了,但是list貌似不起作用。

另据网上找到的解决方案:

http://wxohyer.wordpress.com/2010/04/16/warning-c4251-needs-to-have-dll-interface%E8%A7%A3%E5%86%B3%E5%8A%9E%E6%B3%95/

1:情况一
如果类的定义里面仅含有 编译器内置的类型变量,
int, float 等等. 或者成员函数仅使用了这些变量作为参数, 那么很简单.
直接
class __declspec(dllexport) YourClass
{
}
就行了.

2:情况二
如果类内部使用了别的类, 那么别的类最好也导出, 不然, 首先编译的时候会出现编译警告:
warning C4251: needs to have dll
-interface
意思是,你使用另外的一些类型
/接口, 但是这些类型或接口没有导出. 当你的client使用这些类型/接口的时候, 会出错!
class __declspec(dllexport) YourClass

{
YourAnatherClass m_data;
// 这里会 出现 warning 4251. 如果YourAnatherClass 没有导出的话.
}
解决办法就是: 在YourAnatherClass定义的地方加上
class __declspec(dllexport) YourAnatherClass
{
}
如上, 当你的YourAnatherClass没有导出的时候, dll的使用方会出现链接错误

3:情况三
当类的内部使用了STL模板的时候, 也会出现C4251警告, 情况会有所不同
class __declspec(dllexport) YourClass
{
vector
<int> m_data; // 这里会 出现 warning 4251. 因为vector<int>类型没有被导出
}
上面的使用模板(无论是stl模板,还是自定义模板)的代码,编译dll时会出现C4251警告, 但是dll的使用方, 却不会出现链接错误
!!!
这个因为, dll的使用方那里也有一套模板的定义, 当他们使用那个vector
<int>的时候, 虽没有导出, 但是用户自己也有一套STL模板(或者是自定义的模板),用户会利用自己的模板实例化这个dll中没有导出的东西!

所以, 对于因为使用STL(或模板)出现的c4251警告, 关闭之即可
#pragma warning(push)
#pragma warning(disable:4251)
//your declarations that cause 4251
#pragma warning(pop)

若想不使用通过关闭警告的方式关闭警告, 那么就这样
1)对于用户自定义的模板
template
class DLLImportExportMacro SomeTemplate<int>;
SomeTemplate
<int> y;
2)对于STL的模板
template
class DLLImportExportMacro std::allocator<int>
template
class DLLImportExportMacro std::vector<int, std::allocator<int> >;
vector
<int> m_data;

posted @ 2011-08-01 10:54  旧博客  阅读(725)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3