ow to use DllMain in a MFC dll project (ZZ

How to use DllMain in a MFC dll project (ZZ)

want to add some initial code in DllMain in a MFC dll project, but after I added the code and compiled, there was a link error:

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

DLLMAIN.cpp is the file I created by my own and I define DllMain() in it.

What’s the reason? the linker complains that I have a DllMain in DLLMAIN.cpp but there’s another DllMain in mfcs42d.lib.

So how to use my own DllMain if a MFC dll project?  There’s a quick answer on codeguru , but that article just show the tip without explaining it with more details.

The article says, just copy MFC’s dllmodule.cpp into your own project and compile, it will be OK. It seems to be nonsense but after I tried I found it works. But why? By commenting out unnecessary lines, I find these lines are the key point:
//(dllmodule.cpp)

// The following symbol used to force inclusion of this module for _USRDLL
#ifdef _X86_
extern “C” { int _afxForceUSRDLL; }
#else
extern “C” { int __afxForceUSRDLL; }
#endif

Do you noticed the comment? it forces the inclusion of the module of dllmodule.obj. But how? A searching for _afxForceUSRDLL in MFC source code gives me the answer:
//afx.h

// force inclusion of DLLMODUL.OBJ for _USRDLL
#ifdef _USRDLL
#pragma comment(linker, “/include:__afxForceUSRDLL”)
#endif

Again the MFC designer gives us a good comment: “force inclusion of DLLMODUL.OBJ”, OK, got it.

Now let summary it up:
1)When you try to use MFC library, you surely will include afx.h directly or indirectly
2)then MFC(afx.h) tell the linker to find the symbol of __afxForceUSRDLL and put that object which contains __afxForceUSRDLL into the program, so linker searches and puts dllmodule.obj into my program, for __afxForceUSRDLL is defined in dllmodule.cpp
That’s the common scenario.

Then you want to use your own DllMain in a mfc dll project, linker complains that there are two DllMain, one in your code, one in Dllmodule.obj.

The solution? Tell the linker to add my dllmain.obj for __afxForceUSRDLL. So we define __afxForceUSRDLL in our own cpp file where our own DllMain is defined, then the linker will ignore mfc’s dllmodule.obj and see only one DllMain and never complains.

So the solution is just to add extern “C” { int _afxForceUSRDLL; } in the file where your own DllMain is defined, copying mfc’s dllmodule.cpp is not necessary :-)

收藏 分享 评分
现在努力学习工作,为了将来更加自由得生活。。。
回复 引用

订阅 TOP

How to use DllMain in a MFC dll project (ZZ)

如果开始用了一个SDK的Dll工程,然后为了在这个dll工程里面使用MFC,那么就会出现错误,例如

nafxcw.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in MsgBox.obj

或者

mfcs42.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in MsgBox.obj

为了解决该问题

你只需要在工程设置里面,把

WIN32,NDEBUG,_WINDOWS,_MBCS,_USRDLL,MSGBOX_EXPORTS,_WINDLL,_AFXDLL

中的_USRDLL,删除,就可以正确编译了

现在努力学习工作,为了将来更加自由得生活。。。
回复 引用

TOP

你可能感兴趣的:(ow to use DllMain in a MFC dll project (ZZ)