C++ – Failed to open an FTP connection

cftp

I had a problem when trying to connect and upload a file to an FTP server.

Here's my code:

#include <windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet.lib")

int main()
{
    HINTERNET hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    HINTERNET hFtpSession = InternetConnect(hInternet, L"myserver.com", INTERNET_DEFAULT_FTP_PORT, L"user", L"pass", INTERNET_SERVICE_FTP, 0, 0);

    if(FtpPutFile(hFtpSession, L"file.txt", L"file.txt", FTP_TRANSFER_TYPE_BINARY, 0))
    {
        MessageBox(NULL, L"Upload Complete", L"OK", 0);
    }
    else
    {
        MessageBox(NULL, L"Upload Failed", L"OK", 0);
    }

    InternetCloseHandle(hFtpSession);
    InternetCloseHandle(hInternet);
    return 0;
}

and the error:

svDialog.obj : error LNK2005: "void * hFtpSession" (?hFtpSession@@3PAXA) already defined in MainDlg.obj
svDialog.obj : error LNK2005: "void * hInternet" (?hInternet@@3PAXA) already defined in MainDlg.obj

am I doing wrong?

(the above code is just a simplified representation of my real program using wxWidgets and Multithreading)

Best Answer

There is nothing wrong with code you've posted. Linker error refers to redefined symbol - you have two same variables in global namespace, in two different object files (svDialog and MainDlg).

Try not to use global variables; and if you have to, and you have

HINTERNET hFtpSession;
HINTERNET hInternet;

in one of your headers, then prepend extern, i.e. extern HINTERNET hFtpSesssion; extern HINTERNET hInternet;.

If not, and svDialog's hFtpSession and hInternet are completely different variables, rename them in one of those files (or try anonymous namespace).

Related Topic