多重定义(LNK2005)错误 [英] Multiple Definition (LNK2005) errors

查看:181
本文介绍了多重定义(LNK2005)错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我在两个.cpp文件中都包括这些,但是我得到一个错误,其中声明我定义两次。



全局。 h:

  #pragma once 

//错误相关全域
int SCREEN_LOAD_ERROR = 1 ;
int NO_ERROR = 0;

main.cpp:

  #includeglobals.h
#includecTile.h
/ *其余代码* /
pre>

cTile.h:

  #pragma once 
#includeglobals.h

class cTile {
};

这是抱怨,SCREEN_LOAD_ERROR和NO_ERROR定义两次,但据我所知#pragma一次防止这种情况(我也尝试过#ifndef,但这也没有工作)。



编译器输出:



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



我错过了什么?

解决方案

不要在头文件中声明变量。

在头文件中声明变量时,将在每个包含头文件的转换单元中创建变量的副本。



解决方案是

在一个文件中声明 extern



globals.h:


$

b $ b

  extern int SCREEN_LOAD_ERROR; 
extern int NO_ERROR;

globals.cpp:

  #includeglobals.h
int SCREEN_LOAD_ERROR = 0;
int NO_ERROR = 0;

main.cpp:

  #includeglobals.h

cTile.h:



  #includeglobals.h


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.

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 {
};

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).

compiler output:

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

Am I missing something?

解决方案

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.

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;

main.cpp:

#include "globals.h"

cTile.h:

#include "globals.h"

这篇关于多重定义(LNK2005)错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆