We recommend using Visual Studio 2017

Initializing a DLL


The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at Initializing a DLL.

Typically, your DLL has initialization code (such as allocating memory) that must execute when your DLL loads. When using Visual C++, where you add code to initialize your DLL depends on the type of DLL you are building. If you do not need to add initialization or termination code, there is nothing special you have to do when building your DLL. If you need to initialize your DLL, the following table describes where to add your code.

DLL typeWhere to add initialization and termination code
Regular DLLIn the DLL's CWinApp object's InitInstance and ExitInstance.
Extension DLLIn the DllMain function generated by the MFC DLL Wizard.
Non-MFC DLLIn a function called DllMain that you provide.

In Win32, all DLLs might contain an optional entry-point function (usually called DllMain) that is called for both initialization and termination. This gives you an opportunity to allocate or release additional resources as needed. Windows calls the entry-point function in four situations: process attach, process detach, thread attach, and thread detach.

The C run-time library provides an entry-point function called _DllMainCRTStartup, and it calls DllMain. Depending on the type of DLL, you should have a function called DllMain in your source code or you should use the DllMain provided in the MFC library.

DLLs in Visual C++