Workaround – link fails with multiple instances of DllMain

MSDN: see "PRB: LNK2005 Errors When Link C Run-Time Libs Before MFC Libs", knowledge base ID Q148652.

Circumstances: Create a COM object using ATL, with MFC support enabled. The name of the COM class follows "dll..." alphabetically. Enable proxy/stub code to be included in the DLL, by adding the Wizard generated file DLLDATAX.C to the project. After closing and re-opening the workspace, a link fails with the error:

mfcs42d.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in MSVCRTD.lib(dllmain.obj)

Cause: Visual C++ compiles the source files in alphabetical order, and passes the compiled object files to the linker in alphabetical order. If the linker processes DLLDATAX.OBJ first, the source code references DllMain, which the linker loads from MSVCRTD.LIB(dllmain.obj).

The linker then processes an object file compiled from a C++ file that contains #include "stdafx.h", which references the symbol __afxForceUSRDLL, which the linker loads from MFC42D.LIB(dllmodul.obj). This object module also contains an implementation for DllMain, causing the conflict.

Solutions:

1. Create a C++ source file with a name that appears alphabetically before DLLDATAX.C. This file must contain (at a minimum) the line #include "stdafx.h". The linker processes this file first, and loads the object module MFC42D.LIB(dllmodul.obj), containing the (correct) implementation for DllMain. When the linker processes DLLDATAX.OBJ, the reference to DllMain is linked to the already loaded implementation.

2. Create a header file (named ForceLibs.h, for example) containing code copied from Afx.h, from the line:
#ifndef _AFX_NOFORCE_LIBS
through to:
#endif //!_AFX_NOFORCE_LIBS
inclusive. Edit DLLDATAX.C so that it includes this header file.