简体   繁体   中英

How to declare the function as global using C++?

I am using MFC in Visual Studio. This is the function StartClient, defined in the cpp file, and declared in .h file as

        protected:
      bool StartClient();     // in Client.h file 

          bool CClientSocketDlg::StartClient()      //in Client.cpp file
          {
            CString strServer;
        m_ctlIPAddress.GetWindowText( strServer );
            ------
            -----
            return bSuccess; 
          }

I also declared this

          extern CClientSocketDlg StartClient();  // in global.h

I want to call the StartClient() function in someother xyz.cpp file. That's why i declared this function as global. But it doesnt work.

This give the error :

error LNK2001: unresolved external symbol "class CClientSocketDlg __cdecl StartClient(void)" (?StartClient@@YA?AVCClientSocketDlg@@XZ)

Kindly guide me to resolve that error. Thanks

The declaration

extern CClientSocketDlg StartClient();

tells the compiler that StartClient is a free-standing function that takes no arguments and returns a copy of a CClientSocketDlg object.

The definition

bool CClientSocketDlg::StartClient() { ... }

tells the compiler that the class CClientSocketDlg has a member function named StartClient that takes no arguments and returns a bool .

These two are not the same.

In case of the error, it seems that you are calling the free-standing function, not the member function, and it has only been declared not defined (ie there is no implementation of that function). If you mean to call the StartClient from the class you should declare an object and call the function in the object:

CClientSocketDlg dlg;
dlg.StartClient();

If you mean to call the free-standing you have to implement the function.

您可以使用范围解析运算符来访问C ++中的全局函数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM