c++ exporting and using dll function

后端 未结 2 1420
情书的邮戳
情书的邮戳 2020-12-10 21:50

I can\'t quite figure out where there is a mistake. I am creating a DLL and then using it in a C++ console program (Windows 7, VS2008). But I get LNK2019 unresolved ex

相关标签:
2条回答
  • 2020-12-10 22:41

    You need to import the class not a function. After that, you can call the class member.

    class  __declspec( dllimport ) MyFuncLibInterface {
    
    public:
    
    MyFuncLibInterface();
    ~MyFuncLibInterface();
    
    void myFunc(std::string param);
    
    };
    
    int main(int argc, const char* argv[])
    {
    std::string inputPar = "bla";
    MyFuncLibInterface intf;
    intf.myFunc(inputPar); //this line produces the linker error
    }
    
    0 讨论(0)
  • 2020-12-10 22:43

    You're exporting a class member function void MyFuncLibInterface::myFunc(std::string param); but trying to import a free function void myFunc(std::string param);

    Make sure you #define MyFuncLib_EXPORTS in the DLL project. Make sure you #include "MyFuncLibInterface.h" in the console app without defining MyFuncLib_EXPORTS.

    The DLL project will see:

    class  __declspec(dllexport) MyFuncLibInterface {
    ...
    }:
    

    And the console project will see:

    class  __declspec(dllimport) MyFuncLibInterface {
    ...
    }:
    

    This allows your console project to use the class from the dll.

    EDIT: In response to comment

    #ifndef FooH
    #define FooH
    
    #ifdef BUILDING_THE_DLL
    #define EXPORTED __declspec(dllexport)
    #else
    #define EXPORTED __declspec(dllimport)
    #endif
    
    class EXPORTED Foo {
    public:
      void bar();
    };
    
    
    #endif
    

    In the project which actually implements Foo::bar() BUILDING_THE_DLL must be defined. In the project which tries to use Foo, BUILDING_THE_DLL should not be defined. Both projects must #include "Foo.h", but only the DLL project should contain "Foo.cpp"

    When you then build the DLL, the class Foo and all its members are marked as "exported from this DLL". When you build any other project, the class Foo and all its members are marked as "imported from a DLL"

    0 讨论(0)
提交回复
热议问题