Software & Finance





Visual C++ - Exporting functions in DLL and Static Binding - Linking the .LIB in the client application for the DLL





C++ - Exporting functions in DLL and Static Binding - Linking the .LIB in the client application for the DLL


Most libraries are written as a DLL application so that it can be shared across multiple client applications. I have given the sample code and download link for creating and testing a DLL server and client.

Creating a Test Server DLL application using Visual Studio


  From Visual Studio 2008, use Visual C++ and Win32 and Select Win32 Project as shown below in the screen shot.

 

In the second page Application Settings, Make sure DLL radio button is selected to create TestServer DLL application.

Sample code for the server application to export a function


 

__declspec(dllexport) bool GetWelcomeMessage(char *buf, int len);

 

bool GetWelcomeMessage(char *buf, int len)

{

    if(buf != NULL && len > 48)

    {

        strcpy(buf, "Welcome Message From My First DLL function\n");

        return true;

    }

    return false;

}

Output from Server DLL application


 

  1. TestServer.Lib - This file is used for static linking from the client application
  2. TestServer.DLL - This DLL is required at the run time while testing the client application

Sample code for the client application to import a function


 

__declspec(dllimport) bool GetWelcomeMessage(char *buf, int len);

 

int main()

{

    char buf[128];

    if(GetWelcomeMessage(buf, 128) == true)

        std::cout << buf;

        return 0;

}


The above lines of code will compile but produce a linker error. Use the static link option given below to fix the problem.

 

Static Linking the DLL Server in the client application


Copy the TestServer.Lib and TestServer.Dll to client application folder.

In the client application project settings, select Linker and then Input. Add TestServer.Lib as an addition dependencies.

 

 

 

The above setting will fix the problem and you will see the following output when the run the application.

Welcome Message From My First DLL function

Click here to download the .ZIP file that has both client and server code for testing the DLL.