I'm working in a C workspace in VS2017, having two projects in the workspace: a utility project and a main project that uses the utility project.
After I added a new class (".h" and ".cpp" files) to the utility project, I noticed that although I make changes in the code, the ".lib" file is not rewritten when I build it, unless I change a method whose declaration includes __declspec(dllexport)
. It appears that I have to add this declaration, since otherwise, a derived issue is that of course the main project has linkage errors.
Is there a more elegant way to do it rather than adding __declspec(dllexport)
before the declaration of every public method, like in the code below?
public:
__declspec(dllexport) MyProperty(const std::string &csvLine);
__declspec(dllexport) bool getIsActive();
__declspec(dllexport) std::string getFormatting();
__declspec(dllexport) PropertyType getType();
CodePudding user response:
You can add the declaration to the class, instead of to the individual methods:
class __declspec(dllexport) MyProperty
{
public:
MyProperty(const std::string &csvLine);
bool getIsActive();
std::string getFormatting();
PropertyType getType();
};
Note that for the class, the place is slightly different for methods - not in front of the complete declaration, but between the class
keyword the class name.
As a followup, often a macro is used instead, which is defined to be either __declspec(dllexport)
or __declspec(dllimport)
, depending on some preprocessor condition specifying whether we are currently compiling the dll or trying to use it:
#if defined(MY_DLL)
#define MY_DLL_API __declspec(dllexport)
#else
#define MY_DLL_API __declspec(dllimport)
#endif
class MY_DLL_API MyProperty
{
public:
MyProperty(const std::string &csvLine);
bool getIsActive();
std::string getFormatting();
PropertyType getType();
};
For your dll project, you then define MY_DLL
, and for everyone who just uses the dll (without having MY_DLL
defined), the header will automatically have the required dllimport.