JwG*_*ing 3 c++ variables declaration definition c++14
头
#pragma once
namespace foo
{
int bar;
int funct1();
}
Run Code Online (Sandbox Code Playgroud)
头文件
#include "head.h"
int foo::funct1()
{
return bar;
}
Run Code Online (Sandbox Code Playgroud)
main.cpp
#include <iostream>
#include "head.h"
int main()
{
foo::bar = 1;
std::cout << foo::funct1() << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在head.obj中已经定义的错误LNK2005“ int foo :: bar”(?bar @ foo @@ 3HA)
我不明白发生了什么。我尝试寻找答案,但是每个人的问题都针对他们的代码,甚至看起来都不像我遇到的问题。
我没有将.cpp文件包含到main中。我没有重新定义任何内容。我实际上只是将1分配给变量,然后在同一名称空间中使用函数将其返回。如何多次定义?
标头head.h包含在两个编译单元head.cpp和中main.cpp。因此,变量bar定义了两次。您可以通过以下方式声明没有定义的变量
#pragma once
namespace foo
{
extern int bar;
int funct1();
}
Run Code Online (Sandbox Code Playgroud)
然后在某些cpp模块中定义它。