vc++错误LNK2005已经定义

VC++ Error LNK2005 Already Defined In

本文关键字:定义 LNK2005 错误 vc++      更新时间:2023-10-16

嗨,我目前正在做一个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"

我还创建了游戏对象和图形对象

extern Game TheGame;
extern Graphics TheGraphics

我还声明了一个函数

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:GamesZombie LypseReleaseZombie Lypse.exe : fatal error LNK1169: one or more multiply defined symbols found

请帮忙,我已经到处找过了,我试着自己修理它。还没有。

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

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文件中定义&