我有三个简单的文件。 “香蕉.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/