Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a class in a DLL using std::string. C4251 warning

I would like to implement a simple class in a DLL, something like:

class MY_EXPORT_IMPORT MyClass
{
public:
    //std::string anyPublicStr; //see point 3
protected:
    std::string anyStr;
};

The problem is that Visual C++ compiler (2013 in this case) throws the following warning:

C:...MyClass.hpp:X: warning: C4251: 'MyClass::postfix' : class 'std::basic_string,std::allocator>' needs to have dll-interface to be used by clients of struct 'MyClass'

I read several forums about why this warning is shown and how to solve it. But it is still not clear to me:

  1. Most forums speak about exporting the templates, which make sense for templates, but std::string is already a specific type.
  2. An other page said "Exporting std::string from a DLL is a VERY bad idea, for several reasons." Which make sense.
  3. Others indicate as solution to encapsulate the parameter in a non-inline function. Well, in our case, the std::string is already protected, and switching to private does not solve the warning.

Personally I do not understand why this class could not just statically link the required STL libraries and make it to work without exporting anything. Or if the STL is dynamically linked, it should be also automatically linked in the dll.

Why is this Warning? How to solve it?

like image 389
Adrian Maire Avatar asked Aug 12 '15 09:08

Adrian Maire


1 Answers

std::string is just a typedef:

typedef basic_string<char, char_traits<char>, allocator<char> >
string;

Regarding using STL on the dll interface boundary, generally it is simpler if you avoid that and I personally prefer it if possible. But the compiler is just giving you a warning and it doesn't mean that you will end in a problem. Have a look at: DLLs and STLs and static data (oh my!)

like image 100
Paani Avatar answered Sep 18 '22 17:09

Paani