从 DLL 导出常量
我正在 Windows 上使用 VC9。
我有一个库(我们称之为 libfoo
),它由以下文件组成(为了清楚起见,省略了“include Guards”和“#include”指令):
// foo.hpp
class Foo
{
public:
static const std::string SOME_CONST;
};
以及:
// foo.cpp
#include "foo.hpp"
const std::string Foo::SOME_CONST = "hello";
Foo::SOME_CONST
使用 .def
文件导出。
该库编译良好:生成一个 libfoo.lib
文件和一个 libfoo.dll
文件。
我在示例程序中使用了这个库,例如:
// main.cpp
#include <foo.hpp>
int main()
{
std::cout << Foo::SOME_CONST << std::endl; // std::bad_alloc here
return EXIT_SUCCESS;
}
每当我尝试使用 Foo::SOME_CONST
时,都会抛出 std::bad_alloc
。
仅当我动态链接到libfoo
时才会发生这种情况。 静态链接会产生完美运行的程序。
这里可能发生了什么?以这种方式导出 std::string
常量是否合法?
I'm working with VC9 on Windows.
I have a library (lets call it libfoo
) which is made of the following files ("include guards" and "#include" directives omited for clarity's sake):
// foo.hpp
class Foo
{
public:
static const std::string SOME_CONST;
};
And:
// foo.cpp
#include "foo.hpp"
const std::string Foo::SOME_CONST = "hello";
Foo::SOME_CONST
is exported using a .def
file.
The library compiles fine: a libfoo.lib
file and a libfoo.dll
file are generated.
I used this library in a sample program, like:
// main.cpp
#include <foo.hpp>
int main()
{
std::cout << Foo::SOME_CONST << std::endl; // std::bad_alloc here
return EXIT_SUCCESS;
}
A std::bad_alloc
is thrown whenever I attempt to use Foo::SOME_CONST
.
This only happens if I link dynamically to libfoo
. Linking statically results in a perfectly working program.
What could possibly be going on here ? Is it legal to export a std::string
constant that way ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
检查dll是否确实进行动态初始化,因为可能不会,标准对动态库没有要求。将全局变量包装在静态函数中可能是解决方案。
Check if dll actually does dynamic initialization, because it might not, standard has no requirements for dynamic libraries. Wrapping globals in static functions can be the solution.
使用 __declspec(dllexport) 和 __declspec(dllimport)。不用担心 .def 文件和所有这些垃圾 - 让编译器来完成工作。
Use __declspec(dllexport) and __declspec(dllimport). Stop worrying about .def files and all of that rubbish- let the compiler do the work.
库和主应用程序是否链接到相同版本的标准库和/或 CRT 和/或 MFC,并具有完全相同的设置?我在使用不同版本的 CRT 时遇到了分配问题,并且还解决了由库及其包含的应用程序之间的不同迭代器调试设置引起的错误。
Are the library and the main application linking to the same version of the standard library and/or CRT and/or MFC, with exactly the same settings? I've seen allocation issues when using different versions of the CRT, and also fought bugs caused by different iterator debugging settings between a library and its including application.