LNK2005:已定义的错误 [英] LNK2005: " already defined error

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

问题描述

我试图从分离的.cpp文件中使用全局变量。我有一个init.h文件作为:

I am trying to use a global variable from separated .cpp files. I have got an init.h file as:

//init.h
#ifndef init
#define init
int a = 3;
#endif



我有一个init.cpp文件:
// init.cpp
#include init.h

然后我的main.cpp文件是:

Then finally my main.cpp file is:

//main.cpp
#include "init.h"
int main(void)
{
    while(1)
    {
    }
}


b $ b

之后,我得到错误:

After this, I get the error:

1>init.obj : error LNK2005: "int a" (?a@@3HA) already defined in main.obj
1> ..deneme.exe : fatal error LNK1169: one or more multiply defined symbols found

c $ c> #infdef 控制不能解决这个问题?我也尝试使用 #pragma once 但我有同样的错误。

Why my #infdef control does not solve this problem?. I also tried using #pragma once but I got same error. What is wrong with my code?

推荐答案

您需要将您的变量标记为 extern 并在实现文件中只定义一次。

You need to mark your variable as extern and define it only once in an implementation file.

由于代码现在已经打破了一个定义规则

As the code is now, you're breaking the one definition rule. The include guards don't help in this case, since all translation units that include that header re-define the variable.

你实际需要的是什么:

//init.h
#ifndef init
#define init
extern int a;
#endif

和定义:

//init.cpp
#include "init.h"
int a = 3;

此外,在使用全局变量前考虑两次。你实际上想要实现什么?

Also, think twice before using globals. What is it that you're actually trying to achieve?

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

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