code守卫失败 [英] code guards fail

查看:149
本文介绍了code守卫失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

把这个文件:

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

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?

推荐答案

include防范不保护你免受的确定的对象多次如果您在多个翻译单位的定义!

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:

// header
extern char EL[2];

// TU
#include "header.h"
char EL[2] = "el";

// Other consumer
#include "header.h";
// can now use EL

(也有例外,当然;例如类定义都很好(但类的成员函数定义不是(但内联的是)) - 谨防)

(There are exceptions, of course; e.g. class definitions are fine (but class member function definitions are not (but inlined ones are)) -- beware.)

我要补充一点,或者你可以说静态在你的头文件,使私有定义每个TU:

I should add that alternatively you can say static in your header file to make the definition private to each TU:

// header
static char EL[] = "EL";  // every TU gets a copy

(C ++ 0x中,你不能使用静态链接作为模板参数的对象,虽然。)

(In C++0x you cannot use objects of static linkage as template parameters, though.)

这篇关于code守卫失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆