Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using `__declspec(dllexport)` before every public method

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public:
    __declspec(dllexport) MyProperty(const std::string &csvLine);
    __declspec(dllexport) bool getIsActive();
    __declspec(dllexport) std::string getFormatting();
    __declspec(dllexport) PropertyType getType();

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading