c++ - 多重定义,这里已经定义

标签 c++ visual-c++

我有三个简单的文件。 “香蕉.cc”

namespace ocr{
    int a = 5;
}

“苹果.cc”

#include "banana.cc"

namespace ocr{
    int b = a;
}

“主.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;
}


为什么这会引起重定义? 谢谢。

最佳答案

因为你在你的项目中编译 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 在其中两个文件中定义。

关于c++ - 多重定义,这里已经定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57403133/

相关文章:

C++ - 在 for 循环中没有正确设置值

c++ - DLL 互操作/有趣的错误

C++ 在 lists<string> 和 list<std::pair<string, string>> 之间选择返回类型

c++ - 用 new 定义的数组大小?

c++ - 日志(PCTSTR 格式,...)和日志(PCTSTR 文本): error C2668 ambiguous call to overloaded function

C++ gdb 错误读取变量 : Cannot access memory at address

c++ - 使用 SFML 和纹理构建游戏拒绝绘制

visual-c++ - Visual C++ 中是否有 X64 固有的 8 位原子 CAS (cmpxchg)?

c++ - MSVC 为某些乘法和除法生成奇怪/缓慢的二进制文件

c++ - 我没有得到目录中文件的实际数量。哪里有问题?