Loryan55
Loryan55

Reputation: 325

Compile error "already defined"

It looks like this:

error LNK2005: "unsigned long __cdecl GetModuleBase(void *,
class std::basic_string<char,struct std::char_traits<char>,
class std::allocator<char> > &)" 
(?GetModuleBase@@YAKPAXAAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) 
already defined

And code i have recently added:

#include "Windows.h"
#include <TlHelp32.h>
#include <psapi.h>
#include <string>
#pragma comment(lib, "psapi")
//#pragma comment(lib, "TlHelp32") i could not find where this lib located
using namespace std;

DWORD GetModuleBase(HANDLE hProc, string &sModuleName) 
{ 
   HMODULE *hModules; 
   char szBuf[50]; 
   DWORD cModules; 
   DWORD dwBase = -1; 
   //------ 

   EnumProcessModules(hProc, hModules, 0, &cModules); 
   hModules = new HMODULE[cModules/sizeof(HMODULE)]; 

   if(EnumProcessModules(hProc, hModules, cModules/sizeof(HMODULE), &cModules)) { 
      for(int i = 0; i < cModules/sizeof(HMODULE); i++) { 
         if(GetModuleBaseName(hProc, hModules[i], szBuf, sizeof(szBuf))) { 
            if(sModuleName.compare(szBuf) == 0) { 
               dwBase = (DWORD)hModules[i]; 
               break; 
            } 
         } 
      } 
   } 

   delete[] hModules; 

   return dwBase; 
}

I dont understand what is this, maybe i am using wrong code? Or TlHelp32.lib is needed, but VS says it cannot find such static library.

Upvotes: 0

Views: 514

Answers (2)

GuidedHacking
GuidedHacking

Reputation: 3923

Your GetModuleBase() function is defined twice and the linker is having trouble resolving the conflict. Do a search for "GetModuleBase" and you will find it.

Ideally you will declare the function prototype once in a header like so:

DWORD GetModuleBase(HANDLE hProc, string &sModuleName);

Use header guards or at least this preprocessor directive at the top of your header file:

#pragma once

Then define GetModuleBase() once in a .cpp file, in this .cpp file you need to include the header file. Remove any additional declarations or definitions for this function and your problem should be solved.

Anytime you have this problem the fast solution is to CTRL-F to open the find prompt and search for the function name, you will quickly identify the conflict with this method.

Upvotes: 0

AndrewQ
AndrewQ

Reputation: 420

There is a GetModuleBase function in the namespace Microsoft::WRL.

Your code includes the Microsoft's function (in another part of the project, it's internal), so during link phase it raises an error.

Change the name of the function or use a namespace.

Upvotes: 4

Related Questions