LNK2005 class X 已在 Y.obj 中定义

LNK2005 class X already defined in Y.obj

我有一个启动项目,我需要为其编写自定义分配器和诊断工具。我制作了一个 class Class,其中我有 2 个方法用于自定义分配器 void alloc() void dealloc() 和诊断工具 void evaluate()
现在,我在 CustomAllocator.h 中声明了一个 Class 类型的对象 test 并使用这两种方法毫无问题地分配和释放内存。但是当我尝试在 CustomAllocatorTest.cpp 中调用 evaluate() 方法时,我得到了链接器错误 class Class test(?test@@3VClass@@A) already defined in CustomAllocatorTest.objLNK1169 one or more multiply defined symbols found.

Class.h

#pragma once
class Class
{
public:
    void alloc() { std::cout << "alloc"; }
    void dealloc() { std::cout << "dealloc"; }
    void evaluate() { std::cout << "evaluate"; }
};

CustomAllocator.h

#ifndef _CUSTOM_ALLOCATOR_H_
#define _CUSTOM_ALLOCATOR_H_

#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <stdlib.h>

#include "Class.h"
Class test;

#endif  // _CUSTOM_ALLOCATOR_H_

CustomAllocator.cpp(#include "stdafx.h" 包含 "CustomAllocator.h")

#include "stdafx.h"

using namespace std;

int main()
{
  test.evaluate();
  return 0;
}

在您的文件 CustomAllocator.h 中,您在全局范围内声明 test

#ifndef _CUSTOM_ALLOCATOR_H_
#define _CUSTOM_ALLOCATOR_H_
#include "Class.h"

Class test; // <-- Declaration of test 

#endif 

但是您的 CustomAllocator.h 在很多地方(在 UseCustomAllocator.hCustomAllocator.cpp 中)被包含了很多次,这将对 test 产生 already defined 错误多变的。

请在此处查看如何声明外部全局变量#pragma once doesn't prevent multiple variable definitions