代码保护失败

时间:2011-07-23 23:23:04

标签: c++ c linker-errors include-guards multiple-definition-error

拿这些文件:

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() { }

这只是一个例子,但我确实存在这个问题:

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

为什么以及如何解决?

1 个答案:

答案 0 :(得分:8)

如果您将定义包含在多个翻译单元中,则包含警卫不会保护您多次定义对象!

作为解决方案,永远不要在标头中定义内容,但只有声明

// header
extern char EL[2];

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

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

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


我应该添加,或者您可以在头文件中说static,以使定义对每个TU都是私有的:

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

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