代码守卫失败
拿这个文件:
ah
#ifndef A_H
#define A_H
char EL[] = "el";
#endif
a.cpp
#include "a.h"
b.h
#ifndef B_H
#define B_H
#include "a.h"
#endif
b.cpp
#include "b.h"
main.cpp
#include "b.h"
#include "a.h"
int main() { }
这只是一个例子,但我确实遇到了这个问题:
g++ -c a.cpp
g++ -c b.cpp
g++ -c main.cpp
g++ -o main main.o a.o b.o
a.o:(.data+0x0): multiple definition of `EL'
main.o:(.data+0x0): first defined here
b.o:(.data+0x0): multiple definition of `EL'
main.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status
为什么以及如何解决?
Take this files:
a.h
#ifndef A_H
#define A_H
char EL[] = "el";
#endif
a.cpp
#include "a.h"
b.h
#ifndef B_H
#define B_H
#include "a.h"
#endif
b.cpp
#include "b.h"
main.cpp
#include "b.h"
#include "a.h"
int main() { }
This is only an example, but I've really this problem:
g++ -c a.cpp
g++ -c b.cpp
g++ -c main.cpp
g++ -o main main.o a.o b.o
a.o:(.data+0x0): multiple definition of `EL'
main.o:(.data+0x0): first defined here
b.o:(.data+0x0): multiple definition of `EL'
main.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status
why and how to solve?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您将定义包含在多个翻译单元中,则包含防护并不能保护您避免多次定义对象!
作为解决方案,永远不要在标头中定义内容,而仅声明它们:(
当然也有例外;例如类定义很好(但类成员函数定义则不行) (但内联的是)) - 请注意。)
我应该补充一点,您也可以在头文件中说
static
以使定义对每个 TU 私有:(在 C++0x 中,您不能使用不过,静态链接的对象作为模板参数。)
Include guards don't protect you against defining an object multiple times if you include the definition in multiple translation units!
As a solution, never define things in headers, but only declare them:
(There are exceptions, of course; e.g. class definitions are fine (but class member function definitions are not (but inlined ones are)) -- beware.)
I should add that alternatively you can say
static
in your header file to make the definition private to each TU:(In C++0x you cannot use objects of static linkage as template parameters, though.)