Text

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Monday, August 12, 2019

How to resolve linker error LNK2005

The C runtime libraries define the DllMain function used in all DLL components.  But MFC enabled DLL component projects also have an MFC specific version of this function that gets bound in by default.  So what happens when a project binds with both the DLL versions of the C runtime and the MFC libraries?  Since each of those has their own version of DllMain already defined, there can be a conflict.


LNK2005 _DllMain@12 already defined in MSVCRT.lib(dllmain.obj) mfcs100.lib(dllmodul.obj)

So how can this ever NOT be a problem?  Well, the C runtime DLL is smart enough to use trickerly to protect itself from there already being a DllMain defined at compile time.  This is good, as otherwise none of our "user" DLL components that define their own version of this function could ever bind with the C runtime.

This linker error can still be a problem though, because the MFC libraries do NOT protect themselves from the possibility that this function already exists.  They must think that anyone only ever wrote "pure" MFC components that would never include any other libraries or ever define such functions ourselves.

So to resolve this is a matter of making sure that the MFC libraries are bound first.  How can we do this?


  1. Remove the conflicting libraries from being included by searching the linker search paths in the default manner.
  2. Add the libraries explicitly in a specific order.
In the case of the specific error above, this resolution ends up looking like this:



The two libraries are ignored from among the "default" libraries.  Then they are added as "additional" dependencies instead.  Note that the MFC library is placed first in the Additional Dependencies, followed by the C runtime.  This must be done separately for release mode and debug mode configurations as the libraries are named slightly differently for each mode.

No comments:

Post a Comment