3

嗨,我目前正在使用 C++ 编写程序,而我的 IDE 显然是 VC++,我遇到了这个链接器错误。

error LNK2005: "class Graphics TheGraphics" (?TheGraphics@@3VGraphics@@A) already defined in Game.obj

我查找了如何修复它,但没有一个链接可以修复它。所以我想我自己问你。这些都是我的文件

Game.h
Graphics.h
Inc.h
Main.h

Game.cpp
Graphics.cpp
Main.cpp
WndProc.cpp

在所有头文件中我都有

#ifndef ...
#define...
..
#endif

而且我在头文件中也有一些包含。

在 Inc.h 我在 #ifndef 和 #define 之间有这个

#include <Windows.h>
#include <d3d9.h>
#include <d3dx9.h>

#include "Game.h"
#include "Graphics.h"

在 Main.h 我在 #ifndef 和 #define 之间有这个

#include "Inc.h"

我还创建了对象 Game 和 Graphics 对象

extern Game TheGame;
extern Graphics TheGraphics

我还声明了 1 个函数

LRESULT CALLBACK WndProc(HWND hWnd,
                         UINT Msg,
                         WPARAM wParam,
                         LPARAM lParam);

这是 Main.h

在 Game.h 和 Graphics.h 我在 #ifndef 和 #define 之前有这个

#include "Main.h"

在 Game.h 中,我创建了一个名为 Game 的类和一个名为 GAMESTATE 的枚举。在 Graphics.h 中,我创建了一个名为 Graphics 的类。

该类的所有 .cpp 文件仅包含其类头文件,而 WndProc 包含 Main.h

毕竟我在编译时得到了这个。

1>Graphics.obj : error LNK2005: "class Graphics TheGraphics" (?TheGraphics@@3VGraphics@@A) already defined in Game.obj
1>Graphics.obj : error LNK2005: "class Game TheGame" (?TheGame@@3VGame@@A) already defined in Game.obj
1>Main.obj : error LNK2005: "class Graphics TheGraphics" (?TheGraphics@@3VGraphics@@A) already defined in Game.obj
1>Main.obj : error LNK2005: "class Game TheGame" (?TheGame@@3VGame@@A) already defined in Game.obj
1>WndProc.obj : error LNK2005: "class Graphics TheGraphics" (?TheGraphics@@3VGraphics@@A) already defined in Game.obj
1>WndProc.obj : error LNK2005: "class Game TheGame" (?TheGame@@3VGame@@A) already defined in Game.obj
1>F:\Games\Zombie Lypse\Release\Zombie Lypse.exe : fatal error LNK1169: one or more multiply defined symbols found

请帮助我到处寻找,我试图自己修复它。依然没有。

4

1 回答 1

3

您已经在任何地方外部化了全局变量,但没有在任何地方定义它。

extern不定义变量。它只是告诉编译器该变量是在别处定义的。所以你必须在别处实际定义它。

你可以这样做。

在头文件中

/* main.h */

MYEXTERN Game TheGame;
MYEXTERN Graphics TheGraphics

在第一个 .c 文件中

在 main.cpp

/* MYEXTERN doesn't evaluate to anything, so var gets defined here */
#define MYEXTERN 
#include "main.h"

在其他 .cpp 文件中

/* MYEXTERN evaluates to extern, so var gets externed in all other CPP files */
#define MYEXTERN extern
#include "main.h"

所以它只在一个 .cpp 文件中定义,并在所有其他文件中被外部化。

于 2012-12-30T13:08:52.883 回答