错误LNK2005,已经定义? [英] error LNK2005, already defined?
本文介绍了错误LNK2005,已经定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Win32控制台应用程序中有两个文件,A.cpp和B.cpp。
I have 2 files, A.cpp and B.cpp, in a Win32 console application.
这两个文件只包含以下两行代码: / p>
Both 2 files contain only the following 2 lines of code:
#include "stdafx.h"
int k;
编译时会产生错误
Error 1 error LNK2005: "int k" (?a@@3HA) already defined in A.obj
我不明白发生了什么。
有人可以向我解释一下吗?
Can someone please explain this to me?
推荐答案
为什么会出现此错误
a href =http://en.wikipedia.org/wiki/One_Definition_Rule>一个定义规则 ,因此导致链接错误。
You broke the one definition rule and hence the linking error.
建议的解决方案:
如果你需要在两个cpp文件中相同的命名变量,那么你需要使用Nameless命名空间(匿名命名空间)来避免错误。
If you need the same named variable in the two cpp files then You need to use Nameless namespace(Anonymous Namespace) to avoid the error.
namespace
{
int k;
}
在多个文件中使用相同的变量,那么您需要使用 extern
。
/ p>
A.h
extern int k;
A.cpp
#include "A.h"
int k = 0;
B.cpp
#include "A.h"
//Use `k` anywhere in the file
这篇关于错误LNK2005,已经定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文