### Write Your Own _DLL_InitTerm Function (Windows)

If your DLL requires initialization or termination actions in addition to the actions performed for the runtime environment, you will need to create your own `_DLL_InitTerm` function. The prototype for the _DLL_InitTerm function is:

       unsigned long __stdcall _DLL_InitTerm(HINSTANCE hModule,

         DWORD ulFlag, LPVOID dummy)

The ulFlag variable indicates why the DLL entry point function is being called:

- If ulFlag is equal to DLL_PROCESS_ATTACH (whose value is zero), the DLL environment is initialized.
- If ulFlag is equal to DLL_PROCESS_DETACH (whose value is 1), the DLL environment is terminated.

The hModule parameter is the module handle assigned by the operating system for this DLL. The module handle can be used as a parameter to various Windows API calls.

The return code from _DLL_InitTerm tells the loader if the initialization or termination was performed successfully. If the call was successful, _DLL_InitTerm returns a nonzero value. A return code of `0` indicates that the function failed.

Because it is called by the operating system loader, the _DLL_InitTerm function must be declared as having the _System calling convention.

_DLL_InitTerm functions for Subsystems
A _DLL_InitTerm function for a subsystem DLL has the same prototype, but the content of the function is different because there is no runtime environment to initialize or terminate.

You do not need to call _CRT_init and _CRT_term in your _DLL_InitTerm function, because there is no runtime environment to initialize or terminate. However, if you are using subsystem memory calls, use _rmem_init() or _rmem_term()). If you are coding in C++, you need to call __ctordtorInit at the beginning of _DLL_InitTerm to correctly initialize static constructors and destructors, and __ctordtorTerm at the end to correctly terminate them.

If you change your DLL at a later time to use the regular runtime libraries, you must add calls to _CRT_init and _CRT_term, to ensure that the runtime environment is correctly initialized.

Initializing and Terminating the DLL Environment

Example of a Subsystem _DLL_InitTerm Function
Example of a User-Created _DLL_InitTerm Function