Exporting constants from a DLL
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 F开发者_JAVA技巧oo::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 ?
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.
Use __declspec(dllexport) and __declspec(dllimport). Stop worrying about .def files and all of that rubbish- let the compiler do the work.
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.
精彩评论