Search code examples
visual-c++mfclinkerdllimportdeclspec

LNK2001 unresolved external when importing functions from MFC DLL


I have created an MFC DLL and have exported the functions for example in the file SerialPort.h:

class CSerialPortApp : public CWinApp
{
public:
    CSerialPortApp();

    __declspec(dllexport) int SWrite(unsigned char* toSend, int len);
};

and in my MFC application I want to call the function in SerialInterface.h I have included the "SerialPort.h" from the DLL and called:

__declspec(dllimport) int SWrite(unsigned char* toSend, int len);

class SerialInterface
{
public:

};

for example.

I have added the SerialPort.lib file to my linker includes but when I try to compile I get

error LNK2001: unresolved external symbol "__declspec(dllimport) int __cdecl SWrite(unsigned char*, int)" (__imp_?SWrite@@YAHPAEH@Z)

I am stuck as to the cause of this, I have tried rebuilding everything but nothing seems to help?

Thank you for any help!


Solution

  • Well I found an alternative that works, I believe I was implementing it incorrectly.

    I added a new class to my DLL that was not a CWinApp class:

    class SerialPort
    {
    public:
        __declspec(dllexport) SerialPort(void);
        __declspec(dllexport) virtual ~SerialPort(void);
    
        __declspec(dllexport) int SWrite(unsigned char* toSend, int len);
    };
    

    then included the header for this in my application and the lib and dll etc.

    I then placed the included header file in the main CDialog header but importantly didn't need to import any of the functions:

    #include "SerialPort.h"
    
    class CPPUDlg : public CDialog
    {
    public:
        CPPUDlg(CWnd* pParent = NULL); // standard constructor
    
        SerialPort objSerialPort;
    

    and then in my code I simply call

    objSerialPort.SWrite(toSend, len);
    

    I have not used dllimport to import the functions which I assumed I would need to but it now works!

    Hope this helps anyone who may have a similar problem.