ow to use DllMain in a MFC dll project (ZZ

来源:互联网 发布:中国网络市场交易规模 编辑:程序博客网 时间:2024/06/10 20:46

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.cppinto your own project and compile, it will be OK. It seems to benonsense but after I tried I found it works. But why? By commenting outunnecessary 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

Doyou noticed the comment? it forces the inclusion of the module ofdllmodule.obj. But how? A searching for _afxForceUSRDLL in MFC sourcecode 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)thenMFC(afx.h) tell the linker to find the symbol of __afxForceUSRDLL andput that object which contains __afxForceUSRDLL into the program, solinker searches and puts dllmodule.obj into my program, for__afxForceUSRDLL is defined in dllmodule.cpp
That’s the common scenario.

Thenyou want to use your own DllMain in a mfc dll project, linker complainsthat there are two DllMain, one in your code, one in Dllmodule.obj.

Thesolution? Tell the linker to add my dllmain.obj for __afxForceUSRDLL.So we define __afxForceUSRDLL in our own cpp file where our own DllMainis defined, then the linker will ignore mfc’s dllmodule.obj and seeonly 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

vlight_memeber

Rank: 8Rank: 8

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

原创粉丝点击