遇到lnk2005错误时,我正在使用 namespace 。我不知道如何解决该错误。这是错误:

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;
    }

}

oo
#pragma once

class foo
{
public:
    int ss;
    char* h;

};

图表
#include "Chart.h"

using namespace Chart;

int main ()
{
    l.h = "g";
}

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”作为 namespace 定义。

在Chart.cpp和Source.cpp中都需要表达“命名空间图表”的正确方法是什么,以便所有内容都能编译?

最佳答案

如果您在头文件中定义任何对象并将该头文件包含在多个转换单元中,那么这些对象现在将被定义多次。这是您遇到的问题。 tld的声明引入了对象,并且您已经在头文件中完成了这些操作。

支持 namespace 范围变量的正确方法是在头文件中将它们声明为extern。这使得它们仅是声明,而不是定义。然后,在单个实现文件中定义它们。

Chart.h更改为:

#pragma once

#include "foo.h"

namespace Chart
{
    extern int t;

    extern foo l;

    namespace Bars
    {

        extern int d;
    }

}

然后在一个实现文件(也许是Chart.cpp)中执行以下操作:
int Chart::t;
foo Chart::t;
int Chart::Bars::d;

10-06 13:09
查看更多