命名空间并包含生成链接错误 [英] Namespaces and includes generate link error
问题描述
当我遇到lnk2005错误时,我正在使用命名空间.我不知道如何解决该错误.这是错误:
I was playing around with namespaces when I encountered a lnk2005 error. I can't figure out how to get around the error. Here's the error:
1>Source.obj : error LNK2005: "int Chart::Bars::d" (?d@Bars@Chart@@3HA) already defined in Chart.obj
1>Source.obj : error LNK2005: "class foo Chart::l" (?l@Chart@@3Vfoo@@A) already defined in Chart.obj
1>Source.obj : error LNK2005: "int Chart::t" (?t@Chart@@3HA) already defined in Chart.obj
1>C:\Users\bnm\dev\examples\play\nmspca\Debug\nmspca.exe : fatal error LNK1169: one or more multiply defined symbols found
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.49
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
这是代码...
图表h
#pragma once
#include "foo.h"
namespace Chart
{
int t;
foo l;
namespace Bars
{
int d;
}
}
Foo.h
#pragma once
class foo
{
public:
int ss;
char* h;
};
Chart.cpp
Chart.cpp
#include "Chart.h"
using namespace Chart;
int main ()
{
l.h = "g";
}
Source.cpp
Source.cpp
#include "Chart.h"
using namespace Chart;
int test()
{
l.ss = 0;
return l.ss;
}
从Source.cpp删除#include"Chart.h"时,问题消失了.但是,Source.cpp需要#include"Chart.h"作为名称空间定义.
When the #include "Chart.h" from Source.cpp is removed the problems goes away. However, Source.cpp needs #include "Chart.h" for the namespace definition.
在Chart.cpp和Source.cpp中都需要表达命名空间图表"的正确方法是什么,以便所有内容都能编译?
What's the correct way to express that "namespace Chart" is needed in both Chart.cpp and Source.cpp so that everything compiles?
推荐答案
如果您在头文件中定义任何对象并将该头文件包含在多个转换单元中,则这些对象现在将被定义多次.这是您遇到的问题. t
,l
和d
的声明引入了对象,而您已经在头文件中完成了这些操作.
If you define any objects in a header file and include that header file in multiple translation units, those objects are now defined multiple times. This is the problem you're having. The declarations of t
, l
, and d
introduce objects and you have done so in a header file.
支持名称空间范围变量的正确方法是在头文件中将它们声明为extern
.这使得它们仅是声明,而不是定义.然后,在一个实现文件中定义它们.
The proper method for supporting namespace scope variables is to declare them as extern
in the header file. This makes them declarations only and not definitions. Then, in a single implementation file, define them.
将Chart.h
更改为:
#pragma once
#include "foo.h"
namespace Chart
{
extern int t;
extern foo l;
namespace Bars
{
extern int d;
}
}
然后在实现文件中,也许是Chart.cpp
,执行以下操作:
Then in an implementation file, perhaps Chart.cpp
, do:
int Chart::t;
foo Chart::t;
int Chart::Bars::d;
这篇关于命名空间并包含生成链接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!