I have the below code in stdafx.h.
using namespace std; typedef struct { DWORD address; DWORD size; char file[64]; DWORD line; } ALLOC_INFO; typedef list<ALLOC_INFO*> AllocList; //AllocList *allocList;
Without the commented code (last line), it compiles just fine. But when I add the commented code, Im getting the following error.
error LNK2005: ‘class std::list > * allocList’ (?allocList@@3PAV?$list@PAUALLOC_INFO@@V?$allocator@PAUALLOC_INFO@@@std@@@std@@A) already defined in test.obj
Im using Visual Studio .NET 2003. Anyone has any idea what that is and how to solve it?
Don’t put definitions in header files, just declarations. Declarations specify that something exists while definitions actually define them (by allocating space). For example
typedef,externand function prototypes are all declarations, while things likestruct,intand function bodies are definitions.What’s happening is that you’re most likely including stdafx.h in multiple compilation units (C++ source files) and each of the resulting object files is getting its own copy of
allocList.Then when you link the objects together, there’s two (or more) things called
allocList, hence the link error.You would be better off declaring the variable:
in your header file and defining it somewhere in a C++ source file (such as a
main.cpp):That way, every compilation unit that includes
stdafx.hwill know about the external variable, but it’s only defined in one compilation unit.Based on your further information:
My response is as follows.
I wouldn’t put them in
stdafx.hmyself since I think that uses some MS magic for pre-compiled headers.Make a separate header file
mymemory.hand put your function prototypes in it, for example (note that this has no body):Also in that header, put the other prototypes for
AddTrack(),DumpUnfreed(), etc., and the#define,typedefandexternstatements:Then, in a new file
mymemory.cpp(which also contains#include 'mymemory.h'), put the actual definition ofallocListalong with all the real functions (not just the prototypes) and add that file to your project.Then,
#include 'mymemory.h'in every source file in which you need to track memory (probably all of them). Because there are no definitions in the header file, you won’t get duplicates during the link and because the declarations are there, you won’t get undefined references either.Keep in mind that this won’t track memory leaks in code that you don’t compile (e.g., third-party libraries) but it should let you know about your own problems.