多重定义,已在此处定义

时间:2019-08-07 22:46:02

标签: c++ visual-c++

我有三个简单的文件。 ” banana.cc”

namespace ocr{
    int a = 5;
}

“ apple.cc”

#include "banana.cc"

namespace ocr{
    int b = a;
}

“ main.cc”

#include "apple.cc"
int main()
{
    return 0;
}

/tmp/ccs6XmP2.o:(.data+0x0): multiple definition of `ocr::a'
/tmp/ccEkxDgJ.o:(.data+0x0): first defined here
/tmp/ccs6XmP2.o:(.bss+0x0): multiple definition of `ocr::b'
/tmp/ccEkxDgJ.o:(.bss+0x0): first defined here
/tmp/cco0dUCm.o:(.data+0x0): multiple definition of `ocr::a'
/tmp/ccEkxDgJ.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status

在编译器插入所有#include之后,main.cc类似于:

namespace ocr{
    int a = 5;
}

namespace ocr{
    int b = a;
}

int main()
{
    return 0;
}


为什么这会导致重新定义? 谢谢。

2 个答案:

答案 0 :(得分:1)

因为要在项目中编译apple.cc banana.cc main.cc。

因此,您正在编译此文件:

namespace ocr{
    int a = 5;
}

和此文件:

namespace ocr{
    int a = 5;
}

namespace ocr{
    int b = a;
}

和此文件:

namespace ocr{
    int a = 5;
}

namespace ocr{
    int b = a;
}

int main()
{
    return 0;
}

很显然,在所有三个文件中都定义了ocr::a,在其中两个文件中都定义了ocr::b

答案 1 :(得分:0)

没有足够的声誉来发表评论,但我只是想详细说明一下,以防万一仍然令人困惑。

如果要在文件之间共享一些变量,请创建一个头文件并在其中声明。 即

    // common.h
    namespace ocr{ int a, b; }

    // banana.cc
    #include "common.h"
    void initAppple(){
        ocr::a = 4;
    }
    // apple.cc
    #include "common.h
    void initBanana(){
        ocr::b = a;
    }
    // main.cc
    #include "common.h"
    int main(){ initApple(); initBanana(); }

然后在编译main.cc时,将其与apple.cc和banana.cc链接,而不是“包括”它。

g++ main.cc apple.cc banana.cc -o output

请注意,您不能只在全局范围内单独声明和初始化,这就是为什么您可能需要使用诸如上面的setter函数(initApple()等)的原因。或在头文件中使用extern并在源文件中定义它。