PRB: LNK2005 Errors When Link C Run-Time Libs Before MFC LibsID: Q148652
|
When the C Run-Time (CRT) library and MFC libraries are linked in the wrong order, LNK2005 errors like the following may occur:
nafxcwd.lib(afxmem.obj) : error LNK2005:
"void * __cdecl operator new(unsigned int)"(??2@YAPAXI@Z) already
defined in LIBCMTD.lib(new.obj)
nafxcwd.lib(afxmem.obj) : error LNK2005:
"void __cdecl operator delete(void *)"(??3@YAXPAX@Z) already defined
in LIBCMTD.lib(dbgnew.obj)
nafxcwd.lib(afxmem.obj) : error LNK2005:
"void * __cdecl operator new(unsigned int,int,char const *,int)"
(??2@YAPAXIHPBDH@Z) already defined in LIBCMTD.lib(dbgnew.obj)
mfcs40d.lib(dllmodul.obj): error LNK2005: _DllMain@12 already defined in
MSVCRTD.LIB (dllmain.obj)
mfcs42d.lib(dllmodul.obj): error LNK2005: _DllMain@12 already defined in
msvcrtd.lib(dllmain.obj)
The CRT libraries use weak external linkage for the new, delete, and
DllMain functions. The MFC libraries also contain new, delete, and DllMain
functions, requiring MFC to be linked before the CRT libraries.
For additional information on weak externals, please see the following
article in the Microsoft Knowledge Base:
Q72651 "Weak External" Records: Description, Use, and Errors
There are two ways to resolve this problem. The first solution involves forcing the linker to link the libraries in the correct order. The second solution allows you to find the module that's causing the problem and correct it.
/verbose:lib
This behavior is by design.
When using MFC libraries, you must make sure they are linked before the CRT
library. This can be done by ensuring every file in your project includes
..\Msdev\Mfc\Include\Afx.h first, either directly (#include <Afx.h>) or
indirectly (#include <Stdafx.h>). The Afx.h include file forces the correct
order of the libraries, by using the #pragma comment (lib,"<libname>")
directive.
If the source file has a .c extension, or the file has a .cpp extension but
does not use MFC, you can create and include a small header file
(Forcelib.h) at the top of the module. This new header will ensure the
correct library search order.
Visual C++ does not contain this header file, but you can easily create
this file by performing the following steps:
Keywords : kberrmsg kbGenInfo kbVC kbVC400 kbVC410 kbVC500 kbVC600
Version : WINNT:4.0,4.1,5.0,6.0;
Platform : NT WINDOWS
Issue type : kbprb
Last Reviewed: July 9, 1999