I'm trying to write a .dll library for .dll injection purposes. And because of this fact, it must have a routine called DllMain, since this is what will be used as the entry point. I think my problem may be stemming from the fact that I'm linking in a static library that I've wrote which utilizes a threads and mutexes from afxmt.h. Because somewhere down the line, the inclusion of this is causing the linker to link from mfcs100ud.lib which apparently contains its own version of DllMain.
Here is the file that is giving me trouble:
dllmain.cpp
#include "stdafx.h"
#include <stdio.h>
#include "NamedPipeLogger.h"
static CNamedPipeLogger m_PipeLogger("Log.txt");
BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
}
Here is the stdafx.h file that dllmain.cpp is including.
stdafx.h
#pragma once
#define _AFXDLL
#include <Afx.h>
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
Here is my Error message:
Error 32 error LNK2005: _DllMain#12 already defined in
dllmain.obj D:\xxxxx\xxxxx\xxxxxx\mfcs100ud.lib(dllmodul.obj)
Am I just screwed here because I cannot change the name of my Dll entry point to something other than DllMain?
In many cases this is caused by having _USRDLL in the preprocessor settings, where it should be _LIB. This has to do with 'MFC extension dlls' which I don't think anyone still makes today, yet the VS wizard seems to assume you do want to use this when you check 'Use MFC' in the wizard.
Recently, I experienced the same or a similar issue, and found a solution.
Background
I have an MFC project in Visual Studio 2013 Pro, which generates a DLL. I have several .c modules in the project, which I'm able to do by conditionally specifying the 'extern "C"' construct, disabling precompiled headers for those C files, and - in my case - disabling inherited forced includes, which was pulling-in stdafx.h from the project defaults.
Problem
One day, after having used this method successfully on several C files, when I'd try to add just one more, I'd get the following error.
1>Link:
1> All outputs are up-to-date.
1>mfcs120d.lib(dllmodul.obj) : error LNK2005: _DllMain#12 already defined in MSVCRTD.lib(dllmain.obj)
1> Creating library C:\path\to\project\build_dir\myproj.lib and object C:\path\to\project\build_dir\myproj.exp
1>C:\path\to\project\build_dir\myproj.dll : fatal error LNK1169: one or more multiply defined symbols found
1>
1>Build FAILED.
Solution
I resolved this by implementing "Solution One" from Microsoft Knowledge Base article Q148652, "A LNK2005 error occurs when the CRT library and MFC libraries are linked in the wrong order in Visual C++". This forces the linker to link the libraries in the correct order.
Steps:
Right-click the project, choose Properties.
Ensure you're making changes for All Configurations, and All Platforms.
In the left pane, browse to Linker → Input.
In the right pane, pull down Additional Dependencies, choose <Edit...>.
Add mfcs120d.lib.
Based on the Code Project article Solve error LNK2005: _DllMain#12 already defined in msvcrtd.lib(dllmain.obj) in MFC Projects", I figure I might have to add another library to that list someday, but this much works for me for now.
Well, I guess I threw in the towel on this one (sort of). I was able to at least get by all my problems. I just had to stop using some of the Microsoft classes.
I touched on this in the problem description, but I recall starting to have difficulty with compiling as soon as I started including:
#include <afxmt.h>
#include <afxwin.h>
So I went through and figured out what exactly I was using that required these includes. I was using the AfxBeginThread() method, and the classes CMutex and CCriticalSection. So I figured maybe if I could just get away from any of the proprietary windows stuff that maybe my problems would go away. That means removing all includes of , , and and then address the compilation errors with more standard c++ code. Here is what I did:
Instead of using AfxBeginThread() I used CreateThread().
Instead of using CMutex and CCriticalSection I used the CRITICAL_SECTION structure with its accompanying routines.
After this I was able to compile the .dll and it worked fine.
I got the error when I have moved #include afxdllx.h from dllmain.cpp to StdAfx.h. My project works without this include also
Related
I use MSVC2017 (with MSVC2013 toolchain, if it's matters).
So, I have created new solution with "static lib" project and a console app. At this step it works.
Now, I changed some project's paths for the lib project:
Output directory: $(SolutionDir)BuildDebug
Intermediate directory: $(OutDir)\Debug
I added following includes into pch.h:
#include <windows.h>
#include <inttypes.h>
#include <cstdlib>
#include <stdexcept>
I added reference to my lib and lib's include dir inside console app. Now Studio cannot compile my project, showing a lot of errors about
error C2061: syntax error: identifier 'LONG'
and related.
I found that there is no .pch file anywhere.
I also created test solution with same static lib alone and changed same paths. It seems to compiling successfully, but Intellisense underlines "LONG" with red, saying "it's undefined".
May be someone faced the same problem.
Update: I just tried to create a new solution. I added static lib project, then I added simple file with single function int func(LONG v). It seems to compile. But then I add console app to the solution, link it against static lib, and it's not compile, saying that
error C2065: 'LONG': undeclared identifier
Update 2: I've found that static lib files don't see <windows.h> added into precompiled header. So I included it into my header directly and added typedef struct IUnknown IUnknown; before windows.h, because of new error related to IUnknown. It seems to work. But I still don't understand what is going on.
"Pre-compiled headers" are a build-speed optimization. If they're giving you problems, you can always turn off their use temporarily. When they're turned off, the .pch is no longer used, but the .h is still used.
I expect you'll still have the missing LONG, since it's not even in the .h
For your sanity, it might be useful to use explicit names for your precompiled .h. I'm not sure if VS2017 already uses pch.h by default, or it it still uses stdafx.h. Either way, that's just a default. If you want, you can also rename them to staticlib.h/.pch and executable.h/.pch to avoid confusion. The compiler has no default name for the pch; it relies on compiler switches /Yc (create) and /Yu (use).
When the cuda_test.cu file is not included in the project, the code runs fine.
When such a file is included, I receive the following error message
mfcs100u.lib(dllmodul.obj) : error LNK2005: DllMain already defined in MSVCRT.lib(dllmain.obj)
cuda_test.cu has the following header files, a global function and a wrapper.
#include <cuda.h>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
So I am not sure what causes this problem.
After some research, it seems this problem is fairly common and has
fixes. But this starts giving trouble in a different part of the code. ("StdAfx.h" is included in all .cpp files, if this information is relevant).
It is a huge project written in C++ and I am trying to parallelize some parts of it.
Some help will be hugely appreciated. I can give extra details if needed.
You need to make sure that all parts of your app link against the same runtime.
In Solution Explorer, right click your .cu file and select Properties. Go to CUDA C/C++ > Host and make sure that Runtime Library is set to the same as for the rest of your project.
I'm working my first internship, still trying to get this horrible thing to compile on Visual Studio 2008. I've spent a week playing around with IDE settings and Windows SDK installs and I don't think I'm going to make any more headway in that direction. Everybody is out on vacation here and I have no senior engineers to turn to. Help me Stack Overflow, you're my only hope!
Today, I'm trying to follow the specific errors so I have some idea why everything's breaking. Perhaps then I'll have better insight into how to fix it. For the last couple of hours I've been working on this one:
6>ResizableLib.lib(ResizablePage.obj) : error LNK2001: unresolved external symbol "public: virtual int __thiscall CWnd::Create(char const *,char const *,unsigned long,struct tagRECT const &,class CWnd *,unsigned int,struct CCreateContext *)" (?Create#CWnd##UAEHPBD0KABUtagRECT##PAV1#IPAUCCreateContext###Z)
My understanding is that the CWnd::Create function cannot be found from inside the ResizableLib project which I'm working with. I figured I'd find the file where it was being called, and trace the includes to see if it should have a definition for CWnd::Create at the point where it was being called. I started by searching the entire project (alt+E+F+I) for Create( since I figured this would get every instance where the Create function was being called. I found several other calls to functions that ended with Create, but only one that appeared to be calling the Create function itself:
ResizableGrip.cpp(127): BOOL bRet = m_wndGrip.Create(WS_CHILD | WS_CLIPSIBLINGS
So... I opened up ResizableGrip.cpp and looked at the includes. The first line of the file was:
#include "stdafx.h"
I figured I'd go check out that file to see if there was a function declaration for CWnd::Create, or perhaps some sort of inherited version of it. There were no preprocessor conditions for including this file (as there are at many other points in this program), so I figured it was safe to say that stdafx.h would be included. In order to figure out which stdafx.h file would be included (what is an stdafx.h file typically used for anyway? I see them all over the place!), I first looked in the same directory as the ResizableGrip.cpp file because I believe the compiler first looks in the same directory as the including file before checking the additional includes path in the project, followed last by the include path listed in the main Visual Studio VC++ settings. Is this correct? At any rate, there was an StdAfx.h file located in the same directory, so I concluded that this would be the one that got included. The first few lines of the file looked like this:
#if !defined(AFX_STDAFX_H__0A781DD9_5C37_49E2_A4F5_E517F5B8A621__INCLUDED_)
#define AFX_STDAFX_H__0A781DD9_5C37_49E2_A4F5_E517F5B8A621__INCLUDED_
#pragma message("StdAfx CommonClasses/ResizableLib")
#ifdef INC_DEBUG
#pragma message("In ResizeLib::StdAfx.h")
#endif
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#if _MSC_VER >= 1300
#define WINVER 0x0500
#define _WIN32_WINNT 0x0500
#endif
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#include <afxwin.h> // MFC core and standard components
#include <afxext.h> // MFC extensions
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
I'll admit I don't fully understand all of the preprocessor things that are going on here, but since there are no conditionals surrounding #include , I'd assume that it's getting included too. There was no afxwin.h file in the project directory, so I looked at the additional includes for the project. The only specified place to look was ....\COMMON, so I went two directories out, located the COMMON folder, and looked for afxwin.h. There was nothing there, so I looked in the IDE settings for VC++ directory includes. The first listing was: $(WindowsSdkDir)\include so I looked up the WindowsSdkDir environment variable, which of course didn't exist. I checked in the registry as well. No dice. Eventually I figured out that you can resolve these symbolic names by clicking on one of the ellipses (...) that appear at the far right end of the text fields in the project configuration windows that appear when you click on them and expanding the Macros pane. By doing this, I discovered that $(WindowsSdkDir) was pointing to: C:\Program Files\Microsoft SDKs\Windows\v6.0A\ so I went there, opened up the Include folder, and found no afxwin.h file. $(FrameworkSDKDir)include pointed to the same place as $(WindowsSdkDir)\include, so I proceeded to the next line in the Visual Studio VC++ Directory include list: $(VCInstallDir)atlmfc\include which resolved to C:\Program Files\Microsoft Visual Studio 9.0\VC\atlmfc\include\ where I finally found afxwin.h. In this file there was finally a class called Cwnd with a function called Create defined as such:
virtual BOOL Create(LPCTSTR lpszClassName,
LPCTSTR lpszWindowName, DWORD dwStyle,
const RECT& rect,
CWnd* pParentWnd, UINT nID,
CCreateContext* pContext = NULL);
I have no idea what any of those parameters are, but I'm operating off the assumption that this is an extremely redefined version of the function which the linker was originally whining about:
CWnd::Create(char const *,char const *,unsigned long,struct tagRECT const &,class CWnd *,unsigned int,struct CCreateContext *)
Otherwise, wouldn't the compiler catch this as a different version of the function before the linker took over? Actually, now that I think about it (hence the entire reason for my posting), I guess all I did was walk through the code the same way I'd troubleshoot a compiler error. Did I even do that right? This thing is a monster and I'm just taking guesses here.
So again, like the title says, how are you supposed to follow a linker error? Is there a similar process to what I've done here? The MSDN article makes it sound like this error occurs when the code works fine and the compiler somehow manages to lose the .obj file or .lib file. How can I get it to point to the right place again?
Ugh,
-Alex
A linker error means it's found the header but couldn't find the implementation (obj or lib). There's no point checking whether the header exists - your code has compiled, therefore the compiler found the header.
It looks like you need to link against MFC (ie. the lib that includes the CWnd implementation).
In your project properties, set:
General > Use of MFC > Use MFC in a Shared DLL
As for stdafx.h, it's a precompiled header. You can read up on those yourself. ;) If you don't want it, you can turn it off in project properties:
C/C++ > Precompiled Headers > Precompiled Header > Not Using Precompiled Headers
I am getting this linker error.
mfcs80.lib(dllmodul.obj) : error LNK2005: _DllMain#12 already defined in MSVCRT.lib(dllmain.obj)
Please tell me the correct way of eliminating this bug. I read solution on microsoft support site about this bug but it didnt helped much.
I am using VS 2005 with Platform SDK
I had the same error message, but none of the answers here solved it for me.
So if you Encounter that Problem when creating a DLL Project that uses MFC, it can be resolved by entering the following line:
extern "C" { int _afxForceUSRDLL; }
to the cpp file where DllMain is defined. Then your own DllMain implementation is used, rather than the one from dllmain.obj.
When we try to use MFC library, we surely will include afx.h directly
or indirectly, 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 our
program, because __afxForceUSRDLL is defined in dllmodule.cpp.
That’s the common scenario. When we want to use our own DllMain in a
mfc dll project, linker complains that there are two DllMain, one in
our code, one in Dllmodule.obj.
So we need to tell the linker to add our dllmain.obj for
__afxForceUSRDLL. So we need to 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.
Source: http://social.msdn.microsoft.com/Forums/en-US/0d78aa6b-1e87-4c01-a4a7-691335b7351a/how-to-build-mfc-application-dll-in-visual-c-2010
If you read the linker error thoroughly, and apply some knowledge, you may get there yourself:
The linker links a number of compiled objects and libraries together to get a binary.
Each object/library describes
what symbols it expects to be present in other objects
what symbols it defines
If two objects define the same symbol, you get exactly this linker error. In your case, both mfcs80.lib and MSVCRT.lib define the _DllMain#12 symbol.
Getting rid of the error:
find out which of both libraries you actually need
find out how to tell the linker not to use the other one (using e.g. the tip from James Hopkin)
If you're defining your own DllMain, in your project settings you need to set 'Use of MFC' in the 'Configuration Properties/General' to 'Use Standard Windows Libraries'.
You should do a clean rebuild after changing it.
In my project I was able to solve this problem by adding mfcs80.lib and msvcrt.lib as additional dependencies in the project settings. The 'additional dependencies' can be found under Linker -> Input.
In the debug configuration that would have to be mfcs80d.lib and msvcrtd.lib respectively.
By the way, I am working with Visual Studio 2010, so in my case the MFC lib is called mfc100.lib.
I am not sure why this worked. It is not necessary to add these lib files as additional dependencies because I already set 'Use of MFC' to 'Use MFC in a shared dll'. I guess that by specifying these libraries as additional dependencies they are linked in a different order.
This solution is more or less the same as the one suggested on the Microsoft site: http://support.microsoft.com/kb/148652, except I did not need to type anything in the 'Ignore specific default libraries' box.
For me the direct cause was indeed a missing _afxForceUSRDLL symbol reference, but the indirect cause was a missing _USRDLL macro definition. It is defined by default by the VC wizard, but occasionally devs erase it erroneously.
Here it is in more words.
MSDN knowledge base ID Q148652.
http://support.microsoft.com/kb/148652
Cause:
Visual C++ compiles the source files in alphabetical order, and passes the compiled object files to the linker in alphabetical order.
If the linker processes DLLDATAX.OBJ first, the source code references DllMain, which the linker loads from MSVCRTD.LIB(dllmain.obj).
The linker then processes an object file compiled from a C++ file that contains #include "stdafx.h", which references the symbol
__afxForceUSRDLL, which the linker loads from MFC42D.LIB(dllmodul.obj). This object module also contains an implementation for DllMain,
causing the conflict.
I have a very similar problem. [mfcs110d.lib(dllmodul.obj) : error LNK2005: _DllMain#12 already defined in MSVCRTD.lib(dllmain.obj)] and the solution was add mfcs110d.lib to Additional Dependencies
For all those who are experiencing this error in ATL projects (mostly when trying to add MFC support), here's the solution I found after days of frustration!
First of all, this link was more helpful to me than all the others. It pointed me into the right direction. The problem occurs, if the "generated files" (containing the proxy and stub code, just as the type guids) for some reason have been removed and readded to the project. This causes Visual Studio to add them in the wrong order!
Usually you first come up with the "ATL requires C++ compilation" error, but you may have fixed this by turning out the Yc/Yu (precompiled headers) setting for that file.
What you should do next is unloading your project and edit it. Search for the item groups that define the build and include order (ClCompile and ClInclude). Check their order and settings.
The compiles should appear in this order:
dllmain.cpp (with CompileAsManaged set to false and PrecompiledHeader left empty).
Library source (MyLib.cpp, containing DllCanUnloadNow and so on)
Proxy/Stub code (MyLib_i.c; with same settings as dllmain.cpp)
stdafx.cpp (with PrecompiledHeader set to Create)
All the other library source files (your actual libraries content)
xdlldata.c (with the same settings as dllmain.cpp)
The includes should then be ordered like this:
dllmain.h
MyLib_i.h
Resource.h
stdafx.h
targetver.h
... (actual library headers)
xdlldata.h
Fixing the build order fixed my project and I was able to create a new clean build.
I have personally got rid of this error this way: right-clicked project in the Solution Explorer, selected Properties from pop-up menu, clicked Linker tab and added mfcs71ud.lib into Additional Dependencies. If you're using Visual Studio 2005, it should be "80" instead of "71" and so on.
In my case I had a problem with the preprocessor directives.
For some reason _USRDLL was defined, when it should not have been.
To check this, go to the menu Project , select Project Properties , then select the snippet Configuration Properties --> Preprocessor .
The preprocessor directives will be found there.
Declare the mfc80ud.lib and mfcs80ud.lib in the Additional Dependancies field in the Project Properties -> Linker Tab -> Input of Visual Studio to fix the issue.
Just #undef the _USRDLL before including afx.h, or even better, edit your project configuration and remove the macro.
This is the usual configuration for a MFC extension DLL: Build Settings for an MFC DLL
Make sure you include "Stdafx.h" at the top of each .cpp file. I was getting the exact same error and had a single .cpp file that did not include this header at all. Adding the #include solved the problem.
I found solution Here
Visual Studio 2010 library linking order
this is: /FORCE:MULTIPLE
in linker options
I had to mix ATL and MFC together , to use
[module(name = "mymodule")]; construction in MFC application together with "__hook" keyword
I found this which helped me:
http://support.microsoft.com/kb/148652
Basically the linker order was incorrect. the CRT libs were getting linked before the MFC libs. Turns out, the MFC libs had to get linked FIRST, and then the CRT libs could be linked.
Yucko Microsoft!!
There is a common theme running through some of the answers here.
Avishek Bose:-
Declare the mfc80ud.lib and mfcs80ud.lib in the Additional
Dependancies field in the Project Properties -> Linker Tab -> Input of
Visual Studio to fix the issue.
vmb100:-
I am working with Visual Studio 2010, so in my case the MFC lib is
called mfc100.lib.
joseAndresGomezTovar:-
I have a very similar problem. [mfcs110d.lib(dllmodul.obj) : error
LNK2005: _DllMain#12 already defined in MSVCRTD.lib(dllmain.obj)] and
the solution was add mfcs110d.lib to Additional Dependencies
So the general case seems to be to first find the name of the library to add ...
and then to add it ....
Note that there seem to be some prerequisites and/or alternative solutions.
This can also occur if your solution has multiple projects that export the same symbols. For example if you have sub-project that builds foo.dll with a foo.def file that exports DoFoo and a sub-project for bar.dll with a bar.def file that exports DoFoo, a collision will occur and this is the error you will see when you link.
I've opened an old workspace that is a libray and its test harness. It used to work fine but now doesn't and older versions of the code don't work either with the same errors. I've tried recreating the project and that causes the same errors too. Nothing seems out of order in project settings and the code generated works in the main app.
I've stripped out most of the files and got it down to the bare minimum to generate the error. Unfortunately I can't post the project as this is used in production code.
The LNK2001 linker error I get usually means I've left off a library or forgot to implement a virtual function. However this is part of the standard template library - and is a header at that.
The code that is listed as having the problem in IOCompletionPort.obj doesn't actually use std::string directly, but does call a class that does: Comms::Exception accepts a std::string and the value of GetLastError or WSAGetLastError.
The function mentioned in the error (GetMessage) is implemented, but is a virtual function so other classes can override it if need be. However it appears that the compiler has made it as an Ansi version, but I can't find any options in the settings that would control that. I suspect that might be the problem but since there's very little in the way of options for the library I have no way of knowing for sure. However both projects to specify _MBCS in the compiler options.
--------------------Configuration: TestComms - Win32 Debug-------------------- Linking... Comms.lib(IOCompletionPort.obj)
: error LNK2001: unresolved external symbol "public: virtual class
std::basic_string,class
std::allocator > __thiscall
Comms::Exception::GetMessageA(void)const " (?GetMessageA#
Exception#Comms##UBE?AV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##XZ)
Debug/TestComms.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
TestComms.exe - 2 error(s), 0 warning(s)
Any suggestions? I've lost most of the morning to this and don't want to lose most of the afternoon too.
One possibility lies with Win32 ANSI/Unicode "name-mangling", which turns the symbol GetMessage into either GetMessageA or GetMessageW. There are three possibilities:
Windows.h hasn't been loaded, so GetMessage stays GetMessage
Windows.h was loaded with symbols set for ANSI, so GetMessage becomes GetMessageA
Windows.h was loaded with symbols set for Unicode, so GetMessage becomes GetMessageW
If you've compiled two different files in ways that trigger two different scenarios, you'll get a linker error. The error message indicates that the Comms::Exception class was an instance of #2, above -- perhaps it's used somewhere that windows.h hasn't been loaded?
Other things I'd do in your place, just as a matter of routine:
1) Ensure that my include and library paths don't contain anything that I'm not expecting.
2) Do a "build clean" and then manually verify it, deleting any extra object files if necessary.
3) Make sure there aren't any hardcoded paths in include statements that don't mean what they meant when the project was originally rebuilt.
EDIT: Fighting with the formatting :(
#Curt: I think you came the closest. I haven't tested this but I think I sort of gave the answer in my original question.
GetMessage is a define in Windows.h wrapped in a ifndef block to switch between Ansi (GetMessageA) and Unicode (GetMessageW).
Presuming you haven't futzed around with the Project settings deleting something you ought not have (which is where I'd expect external dependencies like User32.lib to be):
Check Tools | Options | Directories | Libraries (going from memory here) and ensure that you're not missing the common-all-garden variety lib directories (again, without VC6 in front of me, I can't tell you what they are)
This is a general problem with the way Microsoft handled the ANSI vs. Unicode APIs. Since they are all (or pretty much all) done by defining macros for the function names that resolve to the 'A' or 'W' versions of the function names you cannot safely have an identifier in your namespace/class/struct/enum/function that matches a Windows API name.
The windows.h macros run roughshod over all other namespaces.
windows.h is declared at the top of IOCompletionPort.h as an include - I was sick of seeing 7 lines just to include 1 file so I have wrapped it its own file and includes that itself. This also contains some additional #defines (i.e. ULONG_PTR) as our main app won't compile with the Platform SDK installed:-(
That is confirmed. Nothing is out of place.
I've done that - deleted the build directories
I never use hard-coded paths.