多重定义 (LNK2005) 错误

2021-12-31 00:00:00 compiler-errors c++

我最近尝试创建一个全局头文件,其中包含错误代码的所有定义(即 NO_ERROR、SDL_SCREEN_FLIP_ERROR 等),这些只是我将在此处定义的整数.

I recently tried to create a global header file which would have all definitions of error codes (i.e. NO_ERROR, SDL_SCREEN_FLIP_ERROR, etc.) these would just be integers which I would define here.

我在我的两个 .cpp 文件中都包含了这些,但是我收到一个错误,指出我定义了两次.

I included these in both of my .cpp files, however I am getting an error where it is stated that I am defining then twice.

globals.h:

#pragma once

// error related globals
int SCREEN_LOAD_ERROR = 1;
int NO_ERROR = 0;

main.cpp:

#include "globals.h"
#include "cTile.h"
/* rest of the code */

cTile.h:

#pragma once
#include "globals.h"

class cTile {
};

它抱怨 SCREEN_LOAD_ERROR 和 NO_ERROR 被定义了两次,但据我所知,#pragma once 应该可以防止这种情况(我也尝试过 #ifndef,但这也不起作用).

It is complaining that SCREEN_LOAD_ERROR and NO_ERROR are defined twice, but as far as I know #pragma once should prevent this (I also tried #ifndef, but this also did not work).

编译器输出:

1>main.obj : error LNK2005: "int SCREEN_LOAD_ERROR" (?SCREEN_LOAD_ERROR@@3HA) 已经在 cTile.obj 中定义1>main.obj : error LNK2005: "int NO_ERROR" (?NO_ERROR@@3HA) 已经在 cTile.obj 中定义

1>main.obj : error LNK2005: "int SCREEN_LOAD_ERROR" (?SCREEN_LOAD_ERROR@@3HA) already defined in cTile.obj 1>main.obj : error LNK2005: "int NO_ERROR" (?NO_ERROR@@3HA) already defined in cTile.obj

我错过了什么吗?

推荐答案

不要在头文件中声明变量.
当您在头文件中声明变量时,会在包含头文件的每个翻译单元中创建该变量的副本.

Do not declare variables inside your header file.
When you declare a variable in header file a copy of the variable gets created in each translation unit where you include the header file.

解决方案是:
在您的头文件之一中声明它们 extern 并在您的 cpp 文件中定义它们.

Solution is:
Declare them extern inside one of your header file and define them in exactly one of your cpp file.

globals.h:

extern int SCREEN_LOAD_ERROR;
extern int NO_ERROR;

globals.cpp:

#include "globals.h"
int SCREEN_LOAD_ERROR = 0;
int NO_ERROR = 0;

ma??in.cpp:

#include "globals.h"

cTile.h:

#include "globals.h"

相关文章