C ++结构的多重定义 [英] C++ Multiple Definition of Struct
问题描述
我有一个包含简单结构的标头 util.hpp
:
I have header util.hpp
containing a simple struct:
// util.hpp
struct Point {
float x;
float y;
};
两个cpp文件,我们称它们为 a.cpp
和 b.cpp
,它们都包含 util.hpp
:
Two cpp files, let's call them a.cpp
and b.cpp
, both include util.hpp
:
// a.cpp
#include "util.hpp"
void funcA(float _x, float _y) {
Point p;
p.x = _x;
p.y = _y;
// ...
}
// b.cpp
#include "util.hpp"
void funcB(float _x, float _y) {
Point p;
p.x = _x;
p.y = _y;
// ...
}
int main() {
// ...
}
当我分别编译 a.cpp
和 b.cpp
并将它们链接在一起时,我没有任何错误.
When I compile a.cpp
and b.cpp
individually and then link them together I get no errors.
那是为什么?因为我在两个文件中都包含了 util.hpp
,所以我们不是对 struct Point
进行双重定义吗?例如,当我像这样将变量定义添加到 util.hpp
时:
Why is that? Since I include util.hpp
in both files, wouldn't we have a double definition of struct Point
?
When I for example add a variable definition to util.hpp
like this:
// util.hpp
struct Point {
float x;
float y;
};
// New variable
int foo;
链接时出现以下错误:
g++ a.o b.o -o test -O0
b.o:(.bss+0x0): multiple definition of `foo'
a.o:(.bss+0x0): first defined here
这对我来说很有意义,但是为什么结构不会出现相同的错误?
which makes sense to me, but why doesn't the same error occur for the struct?
推荐答案
b.o :(.bss + 0x0):'foo'的多个定义
b.o:(.bss+0x0): multiple definition of `foo'
拥有
// util.hpp
...
// New variable
int foo;
每次包含 util.hpp 时,您再次定义全局变量foo,从而产生错误
each time you include util.hpp you define again the global variable foo, producing your error
只需在头文件中声明( extern int foo;
)并将其定义在一个源文件上
in the header file just declare it (extern int foo;
) and define it on one source file
结构点没有相同的问题,因为这是类型定义,而不是全局变量定义
There is not the same problem for the struct Point because this is a type definition, not a global variable definition
这篇关于C ++结构的多重定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!