LNK2005 ......已在...... .obj中定义

时间:2016-09-12 06:04:04

标签: c++ visual-studio-2015

我是初学C ++程序员,我不知道如何修复此代码。我在Stack OverFlow上找到了问题的原因,但我没有找到适合我案例的解决方案。

错误列表

    LNK2005 "int X::var" (?var@X@@3HA) already defined in HeaderRealiseOne.obj 
    LNK2005 "int Y::var" (?var@Y@@3HA) already defined in HeaderRealiseOne.obj 
    LNK2005 "int Z::var" (?var@Z@@3HA) already defined in HeaderRealiseOne.obj 
    LNK1169 one or more multiply defined symbols found 

的main.cpp

    #include "HeaderInterfaceOne.h"

    int main()
    {
        X::var = 7;
        X::print();

        using namespace Y;

        var = 9;
        print();

        {
            using Z::var;
            using Z::print;

            var = 11;
            print();
        }

        print();

        X::print();

        cout << endl;

        system("pause");
        return 0;
    }

HeaderInterfaceOne.h

    #pragma once

    #include <iostream>
    using namespace std;

    namespace X
    {
        int var;
        void print();
    }

    namespace Y
    {
        int var;
        void print();
    }

    namespace Z
    {
        int var;
        void print();
    }

HeaderRealiseOne.cpp

    #include "HeaderInterfaceOne.h"

    void X::print() { cout << "X = " << X::var << endl; }
    void Y::print() { cout << "Y = " << Y::var << endl; }
    void Z::print() { cout << "Z = " << Z::var << endl; }

首先,我认为我需要在所有名称空间中extern之前添加int var

    namespace X
    {
        extern int var;
        void print();
    }

    namespace Y
    {
        extern int var;
        void print();
    }

    namespace Z
    {
        extern int var;
        void print();
    }

但它引起了另一个问题:

    LNK2001 unresolved external symbol "int X::var" (?var@X@@3HA)
    LNK2001 unresolved external symbol "int X::var" (?var@X@@3HA)

    LNK2001 unresolved external symbol "int Y::var" (?var@Y@@3HA)
    LNK2001 unresolved external symbol "int Y::var" (?var@Y@@3HA)

    LNK2001 unresolved external symbol "int Z::var" (?var@Z@@3HA)
    LNK2001 unresolved external symbol "int Z::var" (?var@Z@@3HA)

    LNK1120 3 unresolved externals

请帮助修复它。

谢谢!

1 个答案:

答案 0 :(得分:0)

第二种方法是正确的。您只需要在.cpp文件中定义extern变量。

添加

int X::var = 0;
int Y::var = 0;
int Z::var = 0;

到HeaderRealiseOne.cpp将解决问题。