_DllMain@12 already defined

I 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 :-)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值