.obj中已经定义的变量;这里发生了什么? [英] Variable already defined in .obj; What is going on here?
问题描述
head.h
#pragma once
namespace foo
{
int bar;
int funct1();
}
head.cpp
#include "head.h"
int foo::funct1()
{
return bar;
}
main.cpp
#include <iostream>
#include "head.h"
int main()
{
foo::bar = 1;
std::cout << foo::funct1() << std::endl;
return 0;
}
在head.obj中已经定义的错误LNK2005"int foo :: bar"(?bar @ foo @@ 3HA)
Error LNK2005 "int foo::bar" (?bar@foo@@3HA) already defined in head.obj
我不知道发生了什么.我尝试寻找答案,但是每个人的问题都针对他们的代码,甚至都没有接近我所遇到的问题.
I don't understand what is going on. I tried looking for the answer but everyone's questions are so specific to their code and don't even look close to the problem that I am having.
我没有将.cpp文件包含到main中.我没有重新定义任何内容.我实际上只是将1分配给变量,然后在同一名称空间中使用函数将其返回.如何多次定义?
I am not including .cpp files into main. I am not redefining anything. I am literally just assigning 1 to the variable then returning it with a function in the same namespace. How is it being defined multiple times?
推荐答案
标头head.h
包含在两个编译单元head.cpp
和main.cpp
中.因此,变量bar
被定义了两次.您可以按照以下方式声明没有定义的变量
The header head.h
is included in two compilation units head.cpp
and main.cpp
. So the variable bar
is defined twice. You could declare the variable without its definition the following way
#pragma once
namespace foo
{
extern int bar;
int funct1();
}
,然后在某些cpp模块中对其进行定义.
and then define it in some cpp module.
这篇关于.obj中已经定义的变量;这里发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!