使用 VS2013 和合适的导出宏,我可以使用此示例代码导出 std::string 和 std::vector:
#ifdef _MSC_VER
// Explicit template exports.
c_EXPORT_TEMPLATE template class c_EXPORT std::allocator<char>;
c_EXPORT_TEMPLATE template struct c_EXPORT std::char_traits<char>;
c_EXPORT_TEMPLATE template class c_EXPORT std::basic_string<char, std::char_traits<char>, std::allocator<char> >;
c_EXPORT_TEMPLATE template class c_EXPORT std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >;
c_EXPORT_TEMPLATE template class c_EXPORT std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >;
#endif
(此处可编译测试用例:https://github.com/rleigh-dundee/dlltest https://github.com/rleigh-dundee/dlltest)--这既可以作为静态库使用,也可以作为 DLL 使用
cmake -G "Visual Studio 12 2013 Win64" -DBUILD_SHARED_LIBS=ON|OFF /path/to/source
使用 VS2015(“Visual Studio 14 2015 Win64”),在使用与 std::string 相关的 DLL 进行编译时收到警告:
c:\users\rleigh\libtest\a.h(30):警告 C4251:
'std::_String_alloc>::_Mypair':
班级
'std::_压缩对>,std::_String_val>,true>'
需要有 dll 接口供类的客户端使用
'std::_String_alloc>'
对于 std::vector 也类似:
C:\Program Files (x86)\Microsoft Visual Studio
14.0\VC\include\vector(679): 警告 C4251: 'std::_Vector_alloc>::_Mypair': 类
'std::_压缩对,std::分配器>>>,std::_Vector_val,std::分配器>>>,true>'
需要有 dll 接口供类的客户端使用
'std::_Vector_alloc>'
虽然在这个人为的测试用例中,这些看似无害并且测试运行良好,但我想修复它们。
更严重的是,如果我使用静态库代替 DLL,链接将完全失败:
c.lib(c.obj) :错误 LNK2001:无法解析的外部符号“public:
静态无符号 __int64 const std::basic_string,类 std::allocator >::npos"
(?npos@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@2_KB)
我在尝试使用 VS2015 构建其他项目时也遇到了后一个错误。
我的问题是:
- VS2015 中字符串和向量类究竟发生了什么变化?
- 我在这里正确导出字符串和向量类吗?我认为它符合这里的指导:https://support.microsoft.com/en-us/kb/168958 https://support.microsoft.com/en-us/kb/168958
- 我应该做哪些更改来修复静态链接错误和 DLL 警告,以便它可以在 VS2015 和 VS2013 中工作? (我将把 2012 年留到另一天,因为它有一系列单独的问题)。
非常感谢您的见解,
罗杰