10.2.1 Creating a Simple Dynamic-link Library

Dynamic-link libraries are typically used to provide common functions that can be used by a number of applications. The following file, myputs.c, contains a simple string-printing function, and a LibMain function that does nothing but return 1.

/*

* File: myputs.c

* Contains library routines for building myputs.dll

*/

#include <windows.h>

INT LibMain(HANDLE hInst, ULONG ul_reasoncalled, LPVOID lpReserved) {

return 1;

UNREFERENCED_PARAMETER(hInst);

UNREFERENCED_PARAMETER(ul_reasoncalled);

UNREFERENCED_PARAMETER(lpReserved);

}

VOID myPuts(LPTSTR lpszMsg) {

DWORD dwWritten;

HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

while (*lpszMsg)

WriteFile(hStdout, lpszMsg++, 1, &dwWritten, NULL);

}

The module-definition file for this DLL is myputs.def, and it contains the following information:

LIBRARY myputs

EXPORTS

myPuts

The LIBRARY statement names the DLL (myputs.dll). The EXPORTS statement indicates that the function myPuts can be used by other applications.

The source code in the file myputs.c is compiled to produce an object module, which is linked to an export file (myputs.exp) to produce the executable DLL module, myputs.dll. The export file is created from the module-definition file, which is also used to create an import library (myputs.lib) that is linked to any executable module (application or DLL) that wants to call the myPuts function. For more information about compiling and linking dynamic link libraries and applications that use them, refer to the documentation for the development tools that you are using.