Search code examples
c++visual-studiodllexportdeclspec

Creating object from class with __declspec(dllexport)


//file.h
# define PartExport __declspec(dllexport)
namespace Part{

class PartExport MyClass : public data::anotherClass{
  MyClass();
  void read();
};
}

I want to access this function by doing this below. Visual studio suggests to do "Part::read();" and f12 to that function works.

//main.cpp
#include <file.h>

int main(){

   Part::read();
   return 0;
}

But when compiling it complains about syntax errors because it thinks that PartExport is the class name. How can I access this function or create an object of MyClass?

edit: I realized that all the syntax errors on the class comes from the #include . I dont know what that means


Solution

  • Your class MyClass is exported, hence you should write in your main :

    Part::MyClass myClass;
    myClass.read();
    

    If you want to call your function as you actually do in your main, you should write in your file.h :

    namespace Part{
    
      void PartExport read();
    
    }
    

    But in this case you will lose your class encapsulation.


    Another thing : to create your dll you have to specify the __declspec(dllexport) to export the function in the library.

    But when your are using it, you should not tell your executable that you want to export this function as it was already exported in your library.

    I advise you to compile your dll defining this macro in your project : PART_EXPORT_DLL

    Then write it like this in your file.h:

    //file.h
    #ifdef PART_EXPORT_DLL
    #    define PartExport __declspec(dllexport)
    #else
    #    define PartExport __declspec(dllimport)
    #endif
    namespace Part{
    
        class PartExport MyClass : public data::anotherClass{
          MyClass();
          void read();
        };
    }
    

    And when you want to import it, be sure not to define PART_EXPORT_DLL