c++ - VC++错误LNK2005已经定义在

标签 c++ visual-c++ include linker-errors

您好,我目前正在开发一个 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

请帮助我到处找,我试着自己修复它。还是什么都没有。

最佳答案

你在任何地方都使用了全局变量,但没有在任何地方定义它。

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 文件中定义并在所有其他文件中被外部化。

关于c++ - VC++错误LNK2005已经定义在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14090827/

相关文章:

visual-c++ - 为什么 vcredist_x86.exe 不能安静地安装?

c++ - 如何处理坏指针

C++:简单的运算符优先级问题还是其他?

php - 需要多个文件

c++ - 如何在不覆盖 CXX 变量的情况下强制 gcc 找到自己的 c++ 头文件?

c++ - 我什么时候需要#include .cpp 文件?

c++ - 指针和多维数组

c++ - 词法和语法分析器软件

c++ - 队列给出错误数据

c++ - 为什么此代码会出现段错误