RWe*_*ndi 2 c++ visual-studio visual-c++
我在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;
Run Code Online (Sandbox Code Playgroud)
没有注释代码(最后一行),它编译得很好.但是当我添加注释代码时,我得到以下错误.
错误LNK2005:"class std :: list>*allocList"(?allocList @@ 3PAV?$ list @ PAUALLOC_INFO @@ V?$ allocator @ PAUALLOC_INFO @@@ std @@@ std @@ A)已在test.obj中定义
我使用Visual Studio .NET 2003.任何人都知道这是什么以及如何解决它?
pax*_*blo 13
不要将定义放在头文件中,只是声明.声明指定在定义实际定义它们时存在某些东西(通过分配空间).例如typedef,extern和函数原型是所有声明,而像struct,int和函数体都是定义.
发生的事情是你最有可能在多个编译单元(C++源文件)中包含stdafx.h,并且每个生成的目标文件都有自己的副本allocList.
然后,当您将对象链接在一起时,会调用两个(或更多)内容allocList,因此会出现链接错误.
你最好声明变量:
extern AllocList *allocList;
Run Code Online (Sandbox Code Playgroud)
在头文件中并在C++源文件(例如a )中的某个位置定义它main.cpp:
AllocList *allocList;
Run Code Online (Sandbox Code Playgroud)
这样,包含的每个编译单元都stdafx.h将知道外部变量,但它只在一个编译单元中定义.
根据您的进一步信息:
我试图关注http://www.flipcode.com/archives/How_To_Find_Memory_Leaks.shtml,我假设所有这些代码都要放在stdafx.h中.还有其他选择,pax?
我的回答如下.
我不会把它们放在stdafx.h自己身上因为我认为它使用了一些MS魔法来预编译头文件.
例如,创建一个单独的头文件mymemory.h并将函数原型放入其中(请注意,这没有正文):
inline void * __cdecl operator new(
unsigned int size,
const char *file,
int line);
Run Code Online (Sandbox Code Playgroud)
也是在这头,把对方原型AddTrack(),DumpUnfreed()等等,和#define,typedef和extern语句:
extern AllocList *allocList;
Run Code Online (Sandbox Code Playgroud)
然后,在一个新文件mymemory.cpp(也包含#include "mymemory.h")中,将实际定义allocList与所有实际函数(不仅仅是原型)放在一起,并将该文件添加到项目中.
然后,#include "mymemory.h"在每个需要跟踪内存的源文件中(可能都是它们).因为头文件中没有定义,所以在链接期间不会出现重复,并且因为声明存在,所以也不会得到未定义的引用.
请记住,这不会跟踪您不编译的代码中的内存泄漏(例如,第三方库),但它应该让您了解自己的问题.
| 归档时间: |
|
| 查看次数: |
3336 次 |
| 最近记录: |